How to execute SQL insert queries to populate database during application start/load?
Asked Answered
E

4

9

I want to load some data into the mysql database during loading of the application. I am using Hibernate for managing database for the application. I can do it in groovy by using Bootstrap but I want to achieve it in Java. I would like to mention that it is Spring MVC based web application.

While searching on the internet, I found that but using hibernate property named as import_file, I can achieve it but I am looking for an alternate route.

Edeline answered 12/4, 2014 at 11:24 Comment(2)
Do you want to populate an embedded database for testing, or are planning on populating a regular database in a non-test environment?Reiners
It is about populating aa regular database. Basically data is related to configurations.Edeline
R
24

You could also take advantage of Spring's DataSourceInitializer . The following is an example of Java Config for it.

@Bean
public DataSourceInitializer dataSourceInitializer() {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));

    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
    dataSourceInitializer.setDataSource(dataSource());
    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
    return dataSourceInitializer;
}
Reiners answered 12/4, 2014 at 21:16 Comment(0)
W
3

Spring already provides a way of initializing databases with content, using a DatabasePopulator. Here's one quick example that I found, for a Spring Batch sample application. The class to look at in that code is ResourceDatabasePopulator. Another example is in Spring Social project samples.

Wraf answered 12/4, 2014 at 14:6 Comment(0)
O
2

I would go for registering an instance of ApplicationListener in the Spring context configuration, that listens for the ContextRefreshedEvent, which is signalled when the application context has finished initializing or being refreshed. After this moment you could setup your database population.

Below you will find the ApplicationListener implementation (which depends on the DAO responsible for performing the database operations) and the Spring configuration (both Java and XML)that you need to achieve this. You need to choose the configuration specific to your app:

Java-based configuration

@Configuration
public class JavaConfig {

    @Bean
    public ApplicationListener<ContextRefreshedEvent> contextInitFinishListener() {
        return new ContextInitFinishListener(personRepository());
    }

    @Bean
    public PersonRepository personRepository() {
        return new PersonRepository();
    }
}

XML

    <bean class="com.package.ContextInitFinishListener">
        <constructor-arg>
            <bean class="com.package.PersonRepository"/>
        </constructor-arg>
    </bean>

This is the code for the ContextInitFinishListener class:

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class ContextInitFinishListener implements ApplicationListener<ContextRefreshedEvent> {

    private PersonRepository personRepository;

    public ContextInitFinishListener(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //populate database with required values, using PersonRepository
    }
}

NOTE: PersonRepository is just a generic DAO for the purpose of the example, it's meant to represent the DAO that YOU use in your app

Outcry answered 12/4, 2014 at 12:1 Comment(0)
S
1

I used as below in my spring boot console application test.

ResourceDatabasePopulator rdp = new ResourceDatabasePopulator();
 rdp.addScript(new ClassPathResource("sql/create-tables.sql"));
 rdp.execute(dataSource);

there are different ways to get datasource depending on type of application or data layered framework.

if u r using spring boot atoconfigured h2 datasource u can use.

@Autowired
Datasource datasource;

to get the data source throgh external configuration class is below

@Value("${spring.datasource.driver-class-name}")
private String driverClass;

@Value("${spring.datasource.url}")
private String dbUrl;

@Value("${spring.datasource.username}")
private String dbUserName;

@Value("${spring.datasource.password}")
private String dbPassword;


@Bean
public DataSource dataSource(){
    SingleConnectionDataSource dataSource = new 
    SingleConnectionDataSource();
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(dbUrl);
    dataSource.setUsername(dbUserName);
    dataSource.setPassword(dbPassword);
    dataSource.setSuppressClose(true);
    dataSource.setAutoCommit(true);
    return dataSource;
}

this worked for me, keep al queries that u need to execute in create-tables.sql

Salt answered 22/3, 2019 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.