How to update a database schema without losing your data with Hibernate?

artemb picture artemb · Apr 10, 2009 · Viewed 22.6k times · Source

Imagine you are developing a Java EE app using Hibernate and JBoss. You have a running server that has some important data on it. You release the next version of the app once in a while (1-2 weeks) and they have a bunch of changes in the persistence layer:

  • New entities
  • Removed entities
  • Attribute type changes
  • Attribute name changes
  • Relationship changes

How do you effectively set up a system that updates the database schema and preserves the data? As far as I know (I may be mistaking), Hibernate doesn't perform alter column, drop/alter constraint.

Thank you, Artem B.

Answer

Nathan Voxland picture Nathan Voxland · Apr 15, 2009

LiquiBase is your best bet. It has a hibernate integration mode that uses Hibernate's hbm2ddl to compare your database and your hibernate mapping, but rather than updating the database automatically, it outputs a liquibase changelog file which can be inspected before actually running.

While more convenient, any tool that does a comparison of your database and your hibernate mappings is going to make mistakes. See http://www.liquibase.org/2007/06/the-problem-with-database-diffs.html for examples. With liquibase you build up a list of database changes as you develop in a format that can survive code with branches and merges.