I defined DataSource as bean:
@Bean(name="dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:~/myDB");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
It works perfectly, however i need to specify schema for db creation and load data on it. Is there any chances how to excute both scripts (schema and data scripts) just like Spring Data has? The Only thing I found is datasource.setSchema()
and aswell as i'm concerned i have to specify full path to it. Then how to specify it, if my schema script located in src/main/resources/
path? (I did exactly, how documentation says, but it fails with a message)
There was an unexpected error (type=Internal Server Error, status=500). org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.h2.jdbc.JdbcSQLException: Schema "~/schema-h2.sql" not found [90079-193]
Thank you for suggestions
You can do something like this :
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
@Bean(name="dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:~/myDB");
dataSource.setUsername("sa");
dataSource.setPassword("");
// schema init
Resource initSchema = new ClassPathResource("script/schema.sql");
DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema);
DatabasePopulatorUtils.execute(databasePopulator, dataSource);
return dataSource;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With