Initialize database without XML configuration, but using @Configuration
The following lines of code inside your @Configuration
class might work.
@Value("classpath:com/foo/sql/db-schema.sql")private Resource schemaScript;@Value("classpath:com/foo/sql/db-test-data.sql")private Resource dataScript;@Beanpublic 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(schemaScript); populator.addScript(dataScript); return populator;}
You have to create your own schema.sql
and put it in your src/main/resources
-folder.
import javax.sql.DataSource;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource;import org.springframework.jdbc.datasource.SimpleDriverDataSource;import org.springframework.jdbc.datasource.init.DatabasePopulator;import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;@Configurationpublic class DataSourceInitializer { @Bean(name = "dataSource") public DataSource getDataSource(){ DataSource dataSource = createDataSource(); DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource); return dataSource; } private DatabasePopulator createDatabasePopulator() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.setContinueOnError(true); databasePopulator.addScript(new ClassPathResource("schema.sql")); return databasePopulator; } private SimpleDriverDataSource createDataSource() { SimpleDriverDataSource simpleDriverDataSource = new SimpleDriverDataSource(); simpleDriverDataSource.setDriverClass(org.h2.Driver.class); simpleDriverDataSource.setUrl("jdbc:h2:target/database/example;AUTO_RECONNECT=TRUE"); simpleDriverDataSource.setUsername(""); simpleDriverDataSource.setPassword(""); return simpleDriverDataSource; }}
After looking at Spring classes related to EmbeddedDatabaseBuilder I found out that the DatabaseBuilder is using some code looking like this:
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();for (String sqlScript: sqlInitializationScripts ) { Resource sqlScriptResource = RESOURCE_LOADER.getResource(sqlScript); populator.addScript(sqlScriptResource);}DatabasePopulatorUtils.execute(populator, dataSource);
This will work fine for me, even if it will be on a @BeforeTest method and not on the Spring configuration.