Reputation: 709
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
The official spring doc says;
In addition, a file named import.sql in the root of the classpath will be executed on startup.
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?
But;
This will also work only if hbm2ddl.auto is set to create or create-drop.
I serached a lot but couldn't find a way. Long stroy short, how can I run .sql statement on startup without destroying database?
Upvotes: 1
Views: 2654
Reputation: 709
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;
How to execute SQL insert queries to populate database during application start/load?
and the answer is
DataSourceInitializer
It works like a charm!
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;
}
Upvotes: 4