Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiple scripts on application startup

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

like image 855
Malakai Avatar asked Dec 07 '22 19:12

Malakai


1 Answers

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;
}
like image 181
victor gallet Avatar answered Dec 30 '22 20:12

victor gallet