finepax007
finepax007

Reputation: 651

Add column in a table mapped using hibernate, without losing existing data

I have a table called Person which I have already mapped in hibernate I has already some data which I do not want to loose. I need to add new column called address, Any idea how to do that in hibernate ?

Thanks in Advance..

Upvotes: 9

Views: 36783

Answers (3)

Randy Stegbauer
Randy Stegbauer

Reputation: 1094

You should also read this other SO question/answer: Hibernate: hbm2ddl.auto=update in production? before you set hibernate.hbm2ddl.auto to update.

Upvotes: 1

Ken Chan
Ken Chan

Reputation: 90457

If you current tables are generated by Hibernate , you can simply add the address property in the java entity class for the address column . Then set the hibernate.hbm2ddl.auto property to update and hibernate will automatically create this column when the SessionFactory is built next time . Hibernate will not change any data store in your database when hibernate.hbm2ddl.auto is update.

Or , you can manually issue the SQL to alter the table structure and then add the address property in the java entity class for the address column.

Upvotes: 7

Mikko Maunu
Mikko Maunu

Reputation: 42084

Likely you are not forced to use Hibernate to create/update database schema. I assume you have something like this in your configuration:

<property name="hibernate.hbm2ddl.auto" value="create-drop" />

Just change value to "validate", perform changes to the mappings and execute ALTER TABLE statements separately.

Other option is to use "update" to let Hibernate figure out how to update your table structure. I suggest to keep it in your hands and just execute DDL SQL manually.

Upvotes: 2

Related Questions