I want to create database schema in hibernate first time. And further, if there is any modification in the schema, like addition of a new table or deletion of some column, I want to update the existing schema keeping the previous data intact.
As per options given at this question, it looks like either I can create schema destroying the previous data, or I can update the schema.
Is there any value which can do both?
Actually I just checked <property name="hibernate.hbm2ddl.auto" value="update" />
is even creating tables for the first time and then later if table/schema exist it does update.
Update
property is applicable when starting or adding a new model. You want to retain the earlier saved entity instances. This is the default schema creation style.
It tries to update the schema, if required. The following updates are supported:
See some of my observations
You can use 'import.sql' .
Add a import.sql file in resource as follow:
/*create database at first time*/
CREATE SCHEMA your-database-name;
and add a line in 'hibernate.cfg.xml' as follow:
<hibernate-configuration>
<session-factory>
...
...
<property name="hbm2ddl.import_files">import.sql</property>
...
...
</session-factory>
</hibernate-configuration>
So, if not exist the database, hibernate creates new db.
I would not recommend updating the db schema based on the entity changes. Try to go with Flyway or Liquibase. You can find similar questions on stackoverflow eg. Hibernate/JPA DB Schema Generation Best Practices
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With