Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 523
artemb Avatar asked Apr 10 '09 15:04

artemb


People also ask

How can I update my whole database without losing data?

If your database is created/updated automatically by some modeling tool, I think the best you way you should do is to understand those changes and write the "alter table" statements yourself and run it in your deployment.


1 Answers

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.

like image 54
Nathan Voxland Avatar answered Sep 23 '22 19:09

Nathan Voxland