问题
I want to deploy a Spring-mvc + Hibernate project, and I want:
- create all database schemas automatically for the first lauch
- update a schema if attributes are added.
- 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