JPA/Hibernate 초기화(ddl-auto, initialization-mode 등)
0. Hibernate
JPA의 구현체로 jpa를 한번 감싸서 사용하기 쉽게 해줌
JPA 소개
1. ORM(Object Relational Mapping) 객체와 관계형 Database를 자동으로 mapping시켜주는 것을 말한다. 객체지향 프로그래밍의 기본 단위는 object 이고 관계형 Datebase의 기본단위는 table이다. 따라서 객..
bsh-developer.tistory.com
1. DDL이란?
데이터 정의어(Data Definition Language)를 의미함.
DataBase의 Table 생성/수정/삭제를 담당하는 명령어
2. ddl-auto 란?
* ddl-auto : 5가지 옵션 제공
create | 항상 새로 생성, persistance context 시작 전 drop --> create , 즉 지우고 다시만듦. |
create-drop | persistance context 띄울 때 create, 종료 후 자동으로 drop = 프로그램 시작시 create, 종료 시 drop = 시작 시 만들고, 종료되면 지움. |
update | 실제 스키마와 entity의 class비교해서 변경에 대한 부분만 반영, 드랍 안함 |
validate | 단순 비교, entity 설정과 스키마가 다른 경우 있으면 오류 발생 |
none | ddl auto 미실행 |
* drop : table/data 삭제
* shcema : DataBase의 전반적인 구조와 제약구조에 대해 명세를 기술한 것.
* Spring : imbeded DB(H2)를 사용하면 기본이 ddl-auto : create-drop
3. generate-ddl
자동으로 엔티티에서 활용하고 있는 테이블을 생성해주는 옵션(h2에서는 자동설정)
4. generate-ddl & ddl-auto
spring:
h2:
console:
enabled: true
jpa:
show-sql: true
properties:
hibernate:
format_sql: true
generate-ddl: true
hibernate:
ddl-auto: create-drop
generate-ddl | ddl-auto |
JPA(인터페이스에 대한 정의) 하위 | hibernate(JPA 구현제) 하위 |
구현체와 상관 없이 자동화된 ddl사용할 수 있도록 설정. | generate-ddl 보다 더욱 세밀한 옵션 |
ddl-auto 사용시 generate-ddl 옵션 무시 |
5. initialization-mode
옵션에 따라 spring에서 지정하는 초기화 모드가 동작한다.
(schema.sql, data.sql로드해서 해당 쿼리 실행해
datasource:
url: jdbc:mysql://localhost:3306/book_manager
username: root
password:
initialization-mode: always
alsways | Always initialize the datasource |
imbedded | Only initialize an embedded datasource. |
none | Do not initialize the datasource |
imbeded db(H2)는 shema.sql, data.sql파일이 resources하위에 있으면 자동으로 가져옴.
흠 만약 db초기화를 하지 않는다면..? none으로 명시해야함.
schema.sql파일있고, initialization-mode : always, ddl-auto: reate-drop이면 어떻게 동작할까
spring에 따르면 schema.sql 파일이 우선순위가 높다. 즉 initialization mode가 always인 경우는 schema.sql파일을 로드할 수 있다. 그러나 schema.sql을 로드해서 schema를 작성하는 것은 ddl-auto와 충돌된다.
이 경우에는 initialization-mode: always가 우선순위가 높다.