Update database schema with hibernate

blow picture blow · Jan 1, 2011 · Viewed 28.4k times · Source
<property name="hibernate.hbm2ddl.auto">update</property>

i can create my database schema, it automatically add properties, constraint, key etc... But what about UPDATE the database schema? If i remove some property from my entities, hibernate doesn't remove it, or if i change some constraint, hibernate doesn't touch constraint already created...

So, there is a way to make hibernate really update the database schema?

Thanks.

Answer

Daniel picture Daniel · Jan 9, 2011

We created a tool for our own that creates the necessary drops of database columns and tables and add these drops to the SQL generated for database updates. But we had to add some extras to the SchemaUpdate generation to make it work:

  • We had to add checks for not-null properties. This includes issuing an UPDATE statement on the data to eleminate nulls where possible, leading to the next point of default values.
  • We had to add checks for default values of columns. The defaults are inferred by the nullability of a column and its datatype. Primitives are always initialized to zero or false, not-null enums to its first enum value, but for other objects the script has to be modified manually.
  • We even added support for resizing varchar columns, because there were cases where the database column length and the @Column(length) differed.

But to put it all together, a complete tool cannot be created this way, because what if a column is renamed in code? What if the type changes in a way not automatically convertible (bool to date?). If you don't have access to a refactoring history, you cannot always propagate changes.