Apostolos
Apostolos

Reputation: 8101

Hibernate and schema update when changing column type

I have Hibernate to set up my entities. For the developer environment I want Hibernate to handle schema updates (mostly some adding new columns, removing or editing column types). When adding a new column Hibernate will add it. Removing a field from the entity won't cause the column to drop from the database. In some posts I've read that this is normal behaviour. But a problem was caused when I tried to edit the type of an entity field:

@Entity
class Person {

    String lastName; //This is the new column
}

This caused Hibernate to add a column of type VARCHAR(255) with default value of NULL and NOT NULL as YES.

The database already had one record (I am testing the behaviour) so Hibernate added the column with the existing behaviour with a value of empty string. I didn't add initialization of the column in the entity's constructor.

Changing the column type to int produced an error. Hibernate raised an IllegalArgumentException trying to add Null value to int field.

I thought Hibernate would drop the column, recreate it, and add Null value with no issue (since int fields can have NULL value). Is it good practice to always give a default value in a column name? Perhaps in a function with PrePersist?

@PrePersist
public void prePersist(){
    this.lastName = 5; //after changing lastName to int.
}

I want to add here that even in development we don't want to drop the table. We want to keep current values.

Upvotes: 3

Views: 4787

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81862

You are using the wrong tool. Hibernate schema migration where never assumed to be a full solution for schema migrations. You might find a solution for the current problem just to stumble on the next.

You should look into a real schema migration tool like liquibase or flyways

Upvotes: 5

Related Questions