AFP_555
AFP_555

Reputation: 2608

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?

EDIT: What I meant is changing the data base directly and reflecting those changes in the Java code. Sorry, I wans't very clear because I didn't know there was another way around.

Upvotes: 5

Views: 11787

Answers (2)

AFP_555
AFP_555

Reputation: 2608

Ok, so I found the way and it's actually VERY EASY.

When we configure a "Code Generation Configuration" in Eclipse's hibernate perspective, that configuration is saved. So, when you run it again, it will create all the "hbm.xml" again from the data base.

So:

  1. Make the changes you need in your database.

  2. Remove the package that contains all your "hbm.xml" (Not sure if required)

  3. Go to the Hibernate perspective and run your configuration again.

  4. Enjoy.

I prefer this way because I don't have to edit many methods and Java logic. I can just create a few relations in my database or add some new columns. Obviously, while developing only.

Upvotes: 0

Elias Garcia
Elias Garcia

Reputation: 7282

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

<property name="hibernate.hbm2ddl.auto">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.

Upvotes: 4

Related Questions