Spring
스프링 프로젝트에서 데이터베이스 데이터 초기화
codinglog
2023. 9. 18. 08:54
프로젝트에 루트에서 다음과 같은 파일을 찾아서 초기화 시 실행한다.
- schema.sql
- data.sql
- schema-${platform}.sql
- data-${platform}.sql
${platform}
은 spring.datasource.platform 의 값을 사용한다.spring.datasource.initialization-mode
속성을 always
로 설정한다.
JPA를 사용한다면 spring.jpa.hibernate.ddl-auto
속성을 none
으로 해야 테이블 자동 생성등을 비활성한다.
이런 방법은 sql이 DATABASE에 따라 변경이 필요할 수 있다.
@PostConstruct
애노테이션으로 메소드를 지정하면 스프링 컨텍스트가 모두 로드 된 후 해당 메소드를 실행하기 때문에 데이터 초기화시 유용하게 사용할 수 있다.
@Component
public class InitData{
private final Repository someRepository;
@PostConstruct
private void loadData(){
someRepository.deleteAll();
repository.save(new SomeEntity(~~~));
}
}
@Component
와 @Profile
을 조합하여 다양한 상황의 데이터를 만들어 낼 수 있을 것이다.
반응형