Backend 취업준비/에러들
JPA sql 파일로 초기화 시 발생 에러
aammddkkzxc
2024. 3. 14. 13:45
- Spring에서 JPA를 사용할 때 @Entity 어노테이션을 사용하면 해당 클래스가 데이터베이스의 테이블을 나타내는 엔티티임을 표시한다.
- Spring Boot에서는 spring.jpa.hibernate.ddl-auto 속성을 통해 DDL 생성 모드를 설정할 수 있다. 이를 통해 데이터베이스 스키마를 자동으로 생성, 업데이트 또는 유지할 수 있다.
- 이 파일은 Spring Boot 애플리케이션이 시작될 때 자동으로 실행. data.sql 파일에는 삽입할 데이터에 대한 SQL 문을 작성할 수 있다. 이를 통해 초기 데이터를 데이터베이스에 로드할 수 있다.
스프링 버전이 올라가면서 스프링 2.5에서 SQL Script DataSource Initialization의 기능이 변경되면서 발생된 문제이다.
스프링 2.5 릴리즈 노트에는 다음과 같은 문구가 있다.
Hibernate and data.sql
By default, data.sql scripts are now run before Hibernate is initialized. This aligns the behavior of basic script-based initialization with that of Flyway and Liquibase. If you want to use data.sql to populate a schema created by Hibernate, set spring.jpa.defer-datasource-initialization to true. While mixing database initialization technologies is not recommended, this will also allow you to use a schema.sql script to build upon a Hibernate-created schema before it’s populated via data.sql.
- 이제 data.sql 스크립트는 hibernate가 초기화되기 전에 실행되며 hibernate에 의해 생성된 스키마에 데이터를 넣기 위해 data.sql을 사용하고 싶으면 spring.jpa.defer-datasource-initialization 이 값을 true로 하라고 되어 있다.
- (단, 데이터 데이터 초기화 기술을 섞는 것을 추천하지는 않는다고 되어있다.)
에러 메세지
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Failed to execute SQL script statement #1 of file [C:\Users\aammddkkzxc\spring-blog-practice\build\resources\main\data.sql]: INSERT INTO article (title, content) VALUES ('제목1', '내용1')
at ~~~~
spring.jpa.defer-datasource-initialization=true
적용시 잘 초기화 된다