JPA/Hibernate: create database schema and import data on first run, update schema on subsequent runs

谁都会走 提交于 2019-12-06 06:09:06

Please keep in mind that using hbm2ddl.auto you can only update the structure of the database, not it's values.

For example: let's say you have

@Version
private Long version;

After a while you find out that you would rather have

@Version
@Temporal(TemporalType.TIMESTAMP)
private Date lastModified;

Hibernate does not have much of a clue about the change in the semantic meaning and for sure would not know how to convert the field accordingly or which default to set.

The properties hbm2ddl.auto and hbm2ddl.import_files are convenient for short lived (in-memory) databases (and thus for automated integration or acceptance tests), but are simply not suitable for production environments.

I would strongly suggest something like scriptella or liquibase. I personally use the latter. Nathan does a great job on the tool, though it's documentation lacks a bit of detail.

That being said:

-Dhibernate.hbm2ddl.auto=create -Dhibernate.hbm2ddl.import_files=foo.sql

on the first start of your app should do the trick. Just set the value of hbm2ddl.auto to update in your persistence.xml.

Just use update -- if the database is empty then the result for update and create is the same.

I had the same problem and I didn't find any Hibernate/JPA solutions. Does any no Hibernate solution an option for you? I can suggest to use liquibase. You may define some initial sqls and then liquibase will execute their on startup. It has an maven pluggin, so you can configure it in your pom and then use it with maven.

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