Spring+Hibernate mysql dataBase initialized with sample data

半世苍凉 提交于 2021-01-29 02:04:17

问题


I want to deploy a Spring-mvc + Hibernate project, and I want:

  1. create all database schemas automatically for the first lauch
  2. update a schema if attributes are added.
  3. add some records in some tables, a root user for USER,ect.

If hibernate.hbm2ddl.auto is set to "create", I will lost previous data every time I restart the project. If set to "update", my import.sql where i put sql to create sample records, won't be executed.

So, what's the best pactice in a "product" environment?


回答1:


hibernate.hbm2ddl.auto is not able to automatically handle more complex database update scenarios, in cases when you want to retain old data.

For production I recommend http://www.liquibase.org/ or https://flywaydb.org/

I have good experience with Liquibase (using it for a few years, in multiple projects).

There is some learning curve, and some duplication (you will have to create DB structure on your own, those tools do not create DB structure from entities).

See http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-execute-liquibase-database-migrations-on-startup for details how to onboard one of those tools.

Even without Spring Boot, is is really simple (just add new library to the classpath, create first script and one Spring Bean).

Edit: IF you are interested in sample project using concepts described above, see https://spring.io/blog/2016/05/31/zero-downtime-deployment-with-a-database

IT describes even more sophisticated scenario- how to update DB without downtime for application.




回答2:


Create a sample_data.sql file with your insert into sql commands.

insert into table(col1,col2) values (val1,val2);
insert into table(col1,col2) values (val1,val2);

Then add property into your database.properties file like below (I assume that your sample_data.sql and database.properties files are in the same directory);

database.hbm2ddl.import_files = sample_data.sql

And the last step is; add the following property into your sessionFactory configuration;

<prop key="hibernate.hbm2ddl.import_files">${database.hbm2ddl.import_files}</prop>


来源:https://stackoverflow.com/questions/37524384/springhibernate-mysql-database-initialized-with-sample-data

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