How To Load Sql Script On Application Startup Using H2 Database

Sometime it might be needed you want to run some SQL script on application startup. For example, you might want to create a table on application startup for Junit set up. In this post, we are going to see how to load SQL script on application startup using h2 database and spring. Here we will see XML based as well annotation-based configuration.

XML based configuration to load SQL script –

Note – Make sure we have myscript.sql file in the resources folder. If not, we need to provide a proper path.

   <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="junitDatasource">
        <property name="driverClassName" value="org.h2.Driver"/>
        <property name="url" value="jdbc:h2:mydb;INIT=RUNSCRIPT FROM 'classpath:myscript.sql';"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

 

Annotation-based configuration to load SQL script –


    @Bean(name="junitDatasource")
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:mydb");
        dataSource.setUsername("sa");
        dataSource.setPassword("");


        Resource initSchema = new ClassPathResource("myscript.sql");
        DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema);
        DatabasePopulatorUtils.execute(databasePopulator, dataSource);

        return dataSource;
    }

 


That’s all about How To Load Sql Script On Application Startup Using H2 Database.