JPA data.sql 초기화 에러 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitiali..
SpringBoot에서 jpa를 사용하여 Entity를 생성시에 @Entity 어노테이션을 사용하여 DDL이 자동으로 생성되도록 설정을 하였고
초기 데이터 적재를 위해 resource 디렉토리 아래 data.sql 파일에 insert 문을 넣고 실행시 아래 에러가 발생했다.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/Users/guda/dev/SpringBoot/workspace/demo/out/production/resources/data.sql]: INSERT INTO book (`title`, `author`, `price`) VALUES ('지금 이대로 좋다', '법류 저', 9330); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "BOOK" not found; SQL statement:처음 공부하는 환경에서 하다 보니 하루동안 삽질 하면서 어떤 문제인지 엄청 삽질을 했다
실행환경 SpringBoot(2.6.4) + Gradle(7.4) + H2(database 2.1.4) + JPA(2.6.4)
결론은 스프링 2.5부터 SQL Script DataSource Initialization이 변경되면서 발생된 문제였다.
schema.sql 및 data.sql 스크립트를 지원하는 데 사용되는 기본 방법이 Spring Boot 2.5에서 재설계되었단다. 
참고한 내용들이 2.5 이전 버전 설정들이여서 정상적으로 작동한 것이다.
해결방안은 application.properties 파일에 아래 설정 값을 추가 하면 된다.
spring.jpa.defer-datasource-initialization=true
<참고사항>
Spring Boot 2.5 Release Notes 를 참고해 보면 아래 와 같은 내용이 나온다.
(https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.5-Release-Notes#hibernate-and-datasql)
기본적으로 data.sql 스크립트는 이제 Hibernate가 초기화되기 전에 실행된다.
data.sql을 사용하여 Hibernate에 의해 생성된 스키마를 채우려면 spring.jpa.defer-datasource-initialization을 true로 설정해라. 
데이터베이스 초기화 기술을 혼합하는 것은 권장되지 않지만 이는 data.sql을 통해 채우기 전에 하이버네이트에서 생성한 스키마를 기반으로 schema.sql 스크립트를 사용할 수도 있습니다.
| Hibernate and data.sqlBy 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. |