How to create database schema in hibernate first time and further update it in case of schema modification?

半腔热情 提交于 2019-11-27 05:01:54
Jayasagar

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

  • Add a field - A new column is added to the table.
  • Rename a field - A new column is added to the table, while the original column remains but is not used any longer. Note: The data from the old column is not migrated to the new column.
  • Remove a field - The column remains but is not used.
  • Change a field type - The type of the column does not change, which may result in type-mismatch exceptions.
  • Create an entity - Creates a new table.
  • Rename an entity - Creates a new table, while the original table remains.
  • Move an entity to another folder - Creates a new table, while the original table remains.
  • Delete an entity - The table remains.

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.

Kris

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!