The order of processes when starting the application

Viewed 91

I have a question about initializing data in Spring-Boot. I have this :

@PostConstruct
    public void run() {
        try {
            upload(path);
            logger.info("Seeding dictionary database...");
        } catch (IOException e) {
            //.....
        }
    }

run() method read .json file and fills the database with information from the file when the app starts. But I also have a .sql file that also fills the database when starts. The table created from initialization from the .sql file is related to the table created from the .json file

When app starts i have

enter image description here

INSERT INTO "USER_DICTIONARY"("DICTIONARY_ID", "USER_ID") VALUES (1, 0)

I have this line in my import.sql but this causes errors because DICTIONARY_ID doesn't exist jet because it comes from .json file which is loaded after import.sql The data retrieved from the .json file is needed to correctly map this table when the sql file is executing.

Is it possible to execute my run() methody before executing .sql file, or can it be solved in some other way ? If so, please help me find the answer.

1 Answers

One option to seed a database is to use the CommandLineRunner in Spring Boot.

Example:

@Component
public class UserDataLoader implements CommandLineRunner {

@Autowired
UserRepository userRepository;

@Override
public void run(String... args) throws Exception {
    loadUserData();
}

private void loadUserData() {
    if (userRepository.count() == 0) {
        User user1 = new User("John", "Doe");
        User user2 = new User("John", "Cook");
        userRepository.save(user1);
        userRepository.save(user2);
    }
    System.out.println(userRepository.count());
}

}

The CommandRunner interface will execute just after the application starts.

Another way is is to use a @EventListener that listens to the application’s ContextRefreshEvent.

Example:

@Component
public class DBSeed {
   @EventListener
   public void seed(ContextRefreshedEvent event) {
     try {
           upload(path);
           logger.info("Seeding dictionary database...");
       } catch (IOException e) {
           //.....
       }
    }
 }
Related