programing

Spring Boot 시작 시 데이터베이스에 샘플 데이터 삽입

padding 2023. 7. 22. 09:32
반응형

Spring Boot 시작 시 데이터베이스에 샘플 데이터 삽입

서버를 시작할 때 테스트 데이터를 만들어 데이터베이스에 삽입하는 올바른 방법은 무엇입니까(JPA/JDBC 백업 Postgres 인스턴스를 사용하고 있습니다).

일반 SQL 코드를 작성하는 것보다 엔터티를 만들고 리포지토리 인터페이스를 통해 엔터티를 유지하는 형태가 좋습니다.RoR의 것과 같은 것.Rake db:seed조력자

만약 프레임워크가 모든 콩이 주입되고 데이터베이스가 준비되었을 때 무언가를 하기 위한 후크를 노출한다면, 그것도 작동할 수 있습니다.

잡으실 수 있습니다ApplicationReadyEvent그런 다음 데모 데이터를 삽입합니다. 예:

@Component
public class DemoData {

    @Autowired
    private final EntityRepository repo;

    @EventListener
    public void appReady(ApplicationReadyEvent event) {

        repo.save(new Entity(...));
    }
}

또는 구현할 수 있습니다.CommandLineRunner또는ApplicationRunner응용 프로그램이 완전히 시작될 때 데모 데이터 로드:

@Component
public class DemoData implements CommandLineRunner {

    @Autowired
    private final EntityRepository repo;

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

        repo.save(new Entity(...));
    }
}

@Component
public class DemoData implements ApplicationRunner {

    @Autowired
    private final EntityRepository repo;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        repo.save(new Entity(...));
    }
}

또는 애플리케이션(또는 다른 'config') 클래스에서 빈 권한처럼 구현할 수도 있습니다.

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner demoData(EntityRepository repo) {
        return args -> { 

            repo.save(new Entity(...));
        }
    }
}

Spring 문서에서: http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/ #사용 방법 초기화

Hibernate를 사용하여 데이터베이스 초기화 Hibernate가 스키마를 처음부터 만드는 경우(즉, ddl-auto 속성이 생성 또는 생성-폐기로 설정된 경우) 시작 시 클래스 경로 루트의 import.sql 파일이 실행됩니다.이 기능은 데모 및 테스트에 사용자가 주의를 기울이는 경우 유용할 수 있지만 프로덕션에서 클래스 경로에 포함되지는 않을 수 있습니다.이 기능은 최대 절전 모드 기능입니다(스프링과는 무관).

이렇게 하면 됩니다.

    @SpringBootApplication
    public class H2Application {

        public static void main(String[] args) {
            SpringApplication.run(H2Application.class, args);
        }

        @Bean
        CommandLineRunner init (StudentRepo studentRepo){
            return args -> {
                List<String> names = Arrays.asList("udara", "sampath");
                names.forEach(name -> studentRepo.save(new Student(name)));
            };
        }
    }

언급URL : https://stackoverflow.com/questions/44749286/spring-boot-insert-sample-data-into-database-upon-startup

반응형