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

前端 未结 4 1282
独厮守ぢ
独厮守ぢ 2020-12-17 02:35

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

4条回答
  •  渐次进展
    2020-12-17 02:50

    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 contextInitFinishListener() {
            return new ContextInitFinishListener(personRepository());
        }
    
        @Bean
        public PersonRepository personRepository() {
            return new PersonRepository();
        }
    }
    

    XML

        
            
                
            
        
    

    This is the code for the ContextInitFinishListener class:

    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    public class ContextInitFinishListener implements ApplicationListener {
    
        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

提交回复
热议问题