[Spring Boot ] Database Initialization
Hibernate를 이용한 초기화
spring.jpa.hibernate.ddl-auto
설정spring.jpa.generate-ddl
(boolean) switches the feature on and off and is vendor independent.spring.jpa.hibernate.ddl-auto
(enum) is a Hibernate feature that controls the behavior in a more fine-grained way. This feature is described in more detail later in this guide.- none — 자동 생성기능을 사용하지 않음
- validate — 테이블, 엔티티 매핑정보를 비교해서 차이가 있으면 경고를 남기고 어플리케이션을 실행하지 않음
- update — 테이블, 엔티티 매핑정보를 비교하여 변경사항을 수정함
- create — 기존 테이블을 삭제하고 새로 테이블을 생성함(DROP + CREATE)
- create-drop — 어플리케이션 종료 시, 생성한 DDL을 제거함(DROP + CREATE + DROP)
- if no schema manager(such as Liquibase or Flyway) is handling the
DataSource
, defaults tocreate-drop
. all other cases, defaults tonone
- ddl-auto 옵션별 설명
DDL Auto
JPA는 DDL generation을 위한 기능을 가지고 있고 이는 2개의 external property에 의해 컨트롤됨
운영환경에서 사용
주로 개발 테스트 환경
Hibernate ddl 에 대한 로그 설정 방법 :
org.hibernate.SQL
to DEBUG- import.sql 파일 생성 시, hibernate가 그 안의 sql들 실행함
SQL Scripts를 이용한 초기화
- Spring Boot can automatically create the schema (DDL scripts) of your JDBC
DataSource
or R2DBCConnectionFactory
and initialize its data (DML scripts).
- SQL database 초기화는 기본값은 embedded 인 메모리 db 일 때만 진행되기에 항상 초기화 하고 싶으면
spring.sql.init.mode
:always
로 설정 필요함
- Hibernate를 이용한 초기화와 Script 를 이용한 초기화 등 여러 개의 Data Source 초기화 기술을 사용하는 것을 추천하진 않지만 Script based
DataSource
초기화를 Hibernate가 만들어낸 스키마에다가 진행하고 싶으면spring.jpa.defer-datasource-initialization
를true
로 설정하기
schema.sql, data.sql
spring: datasource: url: jdbc:sqlserver://localhost:1433;databaseName=virtual_office_test;encrypt=true;trustServerCertificate=true username: sa password: MyPassword@ jpa: show-sql: true hibernate: ddl-auto: none properties: hibernate: format_sql: true sql: init: mode: always value: jwt: secret-string: thisIsTestSecretKeygjJ2a5xVFLJQiM4mZabOqqNTIbI0AhWrWMxWh4NB1pS80Hpfjyd8VXJoefStZpbpDqLKOx4Mq2Vecahu0 expiration-time-minutes: 60
- sql.init.mode : always ⇒ 기본은 embedded database에 대해서만 sql 이 실행되기에, always로 셋팅
- spring.jpa.hibernate.ddl-auto : none ⇒ none으로 설정하지 않으면 schema.sql과 data.sql이 동작한 다음 ddl-auto가 중복 동작하게 됨. 앞에서 적용한 스키마, 데이터 다 날아갈 수 있음
- schema.sql과 data.sql이 hibernate.ddl-auto 보다 먼저 동작하는 것을 주의해야함
- sql.init.platform : 해당 필드에 값이 있으면 spring boot는 schema-${platform}.sql 파일을 이용하여 script를 실행하게 됨
- sql.init.platform: mssql ⇒ schema-mssql.sql 파일을 이용해서 database initialization 을 실행