Search code examples
javajpadb2

How to change a column type in Database and JPA mapping correctly/most safely?


I have the following hibernate field:

@Column(name = MY_COLUMN)
public Long myColumn;

The MY_COLUMN column in a DB2 database is currently defined like this:

ALTER TABLE MY_TABLE
  ADD MY_COLUMN BIGINT;

It turns out that this MY_COLUMN field should have been defined as a DECIMAL(4,1), so I'll have to update that column accordingly in the DB and in the JPA field mapping.

What is the correct/most safe way to do this?

  1. Update the DB first, then JPA mapping
  2. Update the JPA mapping first, then the DB

Please note: I can update the code for the JPA mapping right away, but to change the DB Column I'll need to have the DDL reviewed and executed by others, introducing some lag time.

Things I'm wondering:

  • If the JPA is updated first, will the code just be broken until the DB Column is Altered?

  • Should I wait until the DB Column is updated before pushing the change for the JPA mapping to the remote repo?

  • Is it just bound to be broken either way for some period before they are both changed?

  • Does it depend on the datatypes involved?


Thanks in advance for any insight.


Solution

  • Do you use Flyway or an other DB Migration Tool?

    The way to go is, IMO, alter the db with SQL, and after that, change the JPA entities.

    If you use e.g. Flyway, you can combine this two steps and execute them automatically on the next startup of your application. Nothing is broken this way.

    If you do not use a DB migration tool, you need to prepare your SQL statements, take down the application for the users only, release your new code with new entities and execute the SQL. But I do not recommend this. If you do, create Backups.