Issue
I currently develop a small Java application with help of Spring Boot and Hibernate. As my application evolves, so does the domain model too. Last time I'm facing frequent updates of my domain model - new columns are added to existing tables. This new column addition happens not manually, but automatically via configured hibernate.ddl-auto=update
property, as soon as I introduce new class variable (field) in my entity class.
The problems appear as soon as I add a new @NotNull
annotation at the same time as I introduce new field, what is not surprising: old table entries could not have valid data in the new column without further action, therefore the whole update could result in corrupting database if it succeeds. Especially then, if hibernate first updates the table (by setting @NotNull
constraint on the column), but then finds out that a lot of data in this column is invalid (null
). Because of the hibernate.ddl-auto=update
the corrupted column can not be restored with simple rollback of @NotNull
property on the newly introduced field (i.e. if I comment this annotation out and start the application one more time). This is the reason why I am enforced to drop the whole table with the corrupted data in such situation, what is definitely not the way to do things properly, especially outside of the development environment.
Therefore my question: is there a way to update the existing domain model, such that the constraint @NotNull
will not introduce such problems on newly created fields? What are the best practices for this sort of schema updates, especially if I want to avoid manually updating the whole database schema and want further rely on the hibernate schema creation?
Solution
If you want to set a default value for ALL rows you can set a default value with the @ColumnDefault annotation
If that's not fitting your requirements you might have just discovered one of the reasons why it's actually best practice NOT to rely on schema updater for production purposes at all, see official hibernate documentation - 26. Performance Tuning and Best Practices
Answered By - Mario B