问题描述
我试图弄清楚Spring Hibernate-MySQL的关系.我的目的是,当我启动程序时,它将在类路径中执行 import.sql
文件.我想做到这一点而又不破坏现有表.我发现了一些有关在启动时执行sql文件的文档.
I'm trying to figure out Spring Hibernate - MySQL relationship. My purpose is, when I start the program, it execute the import.sql
file within the classpath. I want to do that without destroy existing tables. I found some documentation about execute sql file on startup.
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html
春季官方文件说;
但是,Spring销毁了我的表,然后执行了import.sql文件.有没有一种方法可以在不丢失现有数据的情况下执行.sql文件?
But, Spring destroy my tables and than execute import.sql file. Is there a way to execute .sql file without lost existing data?
在下面的问题中,他几乎想要和我一样的东西.
In the below question, he almost wanted the same thing like me.
How to import initial data to database with Hibernate?
但是;
我学习了很多,但是找不到方法.长话短说,如何在不破坏数据库的情况下在启动时运行.sql语句?
I serached a lot but couldn't find a way. Long stroy short, how can I run .sql statement on startup without destroying database?
推荐答案
我终于可以找到自己问题的答案.我在项目中使用了基于Java的配置.互联网上与Spring相关的大多数示例都使用基于xml的配置,因此我很难找到问题的答案.
I can finally find the answers for my own question. I used java-based configuration on my project. Most of the examples on the internet related to spring use xml-based configuration, and it is difficult to me find the answers for my questions.
幸运的是我看到了这个问题;
Luckyly I saw this question;
如何执行SQL插入查询以填充应用程序启动/加载期间的数据库?
答案是
它就像一种魅力!
这是在启动时运行SQL语句而不破坏现有数据库的代码段.
Here is the code piece of running SQL statements on startup without destroy existing database.
@Bean
public DataSourceInitializer dataSourceInitializer() {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource());
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}
这篇关于Spring Hibernate MySQL初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!