1

I am new to Spring boot.I want to add some sql while database is creating like seed data.

@Value("classpath:com/foo/sql/db-test-data.sql")
private Resource dataScript;

@Bean
public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
    final DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);
    initializer.setDatabasePopulator(databasePopulator());
    return initializer;
}

private DatabasePopulator databasePopulator() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(dataScript);
    return populator;
}

props.put("hibernate.query.substitutions", "true 1, false 0");
        props.put("hibernate.hbm2ddl.auto", "create-drop");
        props.put("hibernate.show_sql", "false");
        props.put("hibernate.format_sql", "true");

I have perform this action.But it not working on spring boot.Can any one help me.

Charnjeet Singh
  • 3,056
  • 6
  • 35
  • 65

2 Answers2

5

Sometimes spring-boot gets more in the way than it helps; IMHO this is especially so with web applications.

What you can do to get around this is to rename the bean that you define.

@Bean("springBootPleaseStopTellingMeHowYouThinkDataSourceInitializer")
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
    // build it.
}

Now, to turn off the built in bit that looks for data.sql in application.properties

spring.datasource.initialize=false

There, now boot is booted out of the way.

Brett Ryan
  • 26,937
  • 30
  • 128
  • 163
  • I think this is better than the accepted answer because it hints to why the `DataSourceInitializer` isn't working in the original question: because a bean with that ID already exists. A way that I like better as a solution is to rename the method, though, since that's what the bean name is generated from, instead of adding the string literal value to the `@Bean` annotation. But thanks for putting me on the right track anyway. – Sander Verhagen Mar 16 '18 at 20:51
  • In my case , the project was a spring boot project , but not using any of its annotations. There were no application.properties file in the classpath , still DataSourceInitializer bean wouldn't run . Providing a custom name for the DataSourceInitializer bean made it work. This answer provides insight into what is going wrong and its work around. – R.G Nov 10 '19 at 04:06
3

You can take advantage of Spring Boot database initialization capabilities. The simplest way is to place a "data.sql" file in the root of the classpath. So you just need to:

  • Change your sql file name to "data.sql".
  • Place it in "src/main/resources".

Spring Boot will automatically pick up the file and use it to initialize the database on startup.

You can check the documentation if you need to customize the file name, location, etc.

David Lizárraga
  • 1,172
  • 10
  • 17