user2545722 user2545722 - 2 years ago 111
Java Question

How to update Hibernate if database changes

For example, I created the hibernate.cfg.xml and generated the classes automatically (hbm.xml's).

If I realize there's something to be modified, added or deleted from the database, normally I'd have to change the database by hand and then go and change my hbm.xml's source code by hand too.

Is there a way to update without the need to remove the code and re-generate or modify code by hand?

Answer Source

You can let Hibernate updates your database schema when you run your project by adding this line to your hibernate.cfg.xml:

<property name="">update</property>

Options for auto property:

  1. create - It creates new tables corresponding mapping or annotation. It drops existing tables and data.
  2. update - It keeps existing data and tables. It updates schema. here we have to take care contrants.
  3. create-drop - It is same like create but once session gets closed it drops everything.
  4. validate - it validates or matches schema with map or annotation. It's valid for Production environment.

If you want to generate the .xml mappings from your database you can do it using reverse JDBC with Hibernate Tools. You only need to specify your database connection info.

This page have a great example on that:

Reverse JDBC with Hibernate Tools

You can choose whatever you want, but it's much better, portable and easy to use the first option.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download