Hibernation and schema update when column type changes
I have Hibernate to set up my entities. For a developer environment, I want Hibernate to handle schema updates (mostly some add new columns, delete or edit column types). When adding a new column, Hibernate will add it. Removing a field from an object will not remove the column from the database. I have read in some posts that this is normal behavior. But the problem was caused when I tried to change the field type of the object:
@Entity
class Person {
String lastName; //This is the new column
}
This caused Hibernate to add a VARCHAR (255) column with default NULL and NOT NULL as YES.
There was already one record in the database (I'm testing the behavior), so Hibernate added a column with the existing behavior with an empty string value. I did not add column initialization in the entity constructor.
Changing the column type to int
has failed. Hibernate brought up IllegalArgumentException
trying to add a Null value to an int field.
I thought Hibernate would delete the column, recreate it and add a Null value without issue (since int fields can be NULL). Is it good practice to always give a default in the 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 give up the table. We want to keep the current values.
source to share