Artur Rem
Artur Rem

Reputation: 219

Hibernate Database changes

we are using Hibernate to get Data from a DB. The Problem is that we have sometimes to change our Tables. Infact of that we got several times the Problem that the Database Mapping from Hibernate is not valid with the database.

Can someone give me a hint how to solve that problem?

Simple Example:

Today User Table looks like:

In the Futur it can look like:

It's important to hold it easy as possible.

We're using MsSQL and XML Mapping.

Im thankfull for every contructiv Answer.

Upvotes: 3

Views: 1386

Answers (2)

Aniket Kulkarni
Aniket Kulkarni

Reputation: 12983

In hibernate.cfg.xml file add property :

<property name="hibernate.hbm2ddl.auto">update</property>

Available values :

validate | update | create | create-drop

By using this property you need to change the POJO and .hbm.xml files it will automatically update to database.

There is difference between create and update is that, update will update your database if database tables are already created and will create if database tables are not created.

create will create tables in database even though tables are already exists, it will drop all the tables and create tables again resulting in previously inserted data loss.

Upvotes: 2

Ashley Frieze
Ashley Frieze

Reputation: 5443

If your database and your OO code are being managed independently, then you probably cannot avoid this issue. However, if you're trying to evolve your data model centrally then you have a choice to make - do it from the OO side first, and get the database up to date, or modify the database and update the mappings in the OO side.

If you focus just on the DB then the mappings will just have to catch up. If you want to do this easier, then evolve the OO model and make sure the mappings you use make sense - use the DDL generation capability of hibernate to either automatically update the database, or write the DDL to a fresh DB so you can use DB comparison tools to propagate the updates.

Big changes will be breaking changes - it's pretty much unavoidable. In general, if your DB is purely there to support an OO system, then I would recommend designing it from the OO mapping first.

Upvotes: 1

Related Questions