Spring Boot 2.5.x, Hibernate, data.sql 스크립트 실행 이슈

ahnjs·2022년 7월 21일
0
post-thumbnail

개요

사이드 프로젝트를 진행하면서 임시로 카테고리와 토픽 데이터를 초기화해줄 필요성이 생겼다. ddl-auto 값을 create-drop으로 설정했기 때문에 resources 폴더 하위에 data.sql 파일을 생성하여 초기화를 시도했더니 다음과 같은 에러가 발생했다.

기존 프로젝트와 다른점을 찾아보니 스프링부트 버전이 달랐고 관련해서 찾아보았다.

문제 원인

Spring Boot 2.5 Release Notes

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.

스프링부트 2.5 릴리스 노트 일부분이다. 내용을 확인하니 Spring Boot 2.5.x 버전부터는 data.sql 스크립트가 Hibernate가 초기화되기 전에 실행된다라고 쓰여있다. (Flyway 및 Liquibase의 동작과 동일) 때문에 스키마가 생성되기 이전에 스크립트가 실행이되면서 에러가 발생했다.

해결방법

Spring Boot 설정파일에 spring.jpa.defer-datasource-initialization의 값을 true 값으로 설정해 줘야한다.
또는 schema.sql을 추가해서 Hibernate가 초기화 되기 이전에 스키마를 생성하는 방법이 있는데, DB 초기화를 혼합하여 사용하는 방법은 권장하지 않는 방법이라 한다.

0개의 댓글