H2 데이터 베이스 연결(*.yml)
초기 개발 환경에서 h2 inmemory 데이터 베이스를 활용하여 테이블 생성 및 샘플 데이터 입력할 수 있도록 설정 수행
1. 의존성 추가 (build.gradle)
dependencies {
// spring boot
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// lombok
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
// h2
runtimeOnly 'com.h2database:h2'
}
2. application.yml 작성
- (주의) 파일명이 틀리거나, yml 파일내에 들여쓰기가 잘못될 경우 정상 동작하지 않을 수 있음
- ddl-auto 의 경우 default 로 none을 설정하고 profile에 따라 분기됨
=> 프로덕션에서 ddl-auto 활성화 되면 큰 사고로 이어지니 좋은 방식인 듯 하다
spring:
profiles:
default: local
datasource:
url: jdbc:h2:mem:~/testdb
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
hibernate:
ddl-auto: none
server:
port: 8080
---
spring:
config:
activate:
on-profile: local
jpa:
hibernate:
ddl-auto: create
show-sql: true
properties:
hibernate:
format_sql: true
defer-datasource-initialization: true
database-platform: org.hibernate.dialect.H2Dialect
h2:
console:
enabled: true
3. sql scripts 사용한 데이터 초기화
- spring boot 2.5 이후 부터 아래 속성 추가됨
- Hibernate 초기화 이후 main/resource/{scheme||data}.sql 파일을 실행하도록 하는 설정
spring.jpa.defer-datasource-initialization: true
참고. 공식 reference
“How-to” Guides
Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s spring-jcl module. To use Logback, you need to include it and spring-jcl on the classpath. The recommended way to do th
docs.spring.io
참고. h2 모드에 대해
- Embedded mode
- Server mode
- Mixed mode
[H2]설정하기(모드, 포트)
참고:[H2]H2의 설명과 설치하는 법 [H2]사용하기 사실 H2는 경량DB기 때문에 설정할게 별로 없긴 하다.그런데 필자의 경우 사용하다보니까 2가지의 설정을 해줘야 했었는데 첫번째는 모드였고 두번
kamang-it.tistory.com
Embedded Mode(임베디드 모드)
In embedded mode, an application opens a database from within the same JVM using JDBC. This is the fastest and easiest connection mode. The disadvantage is that a database may only be open in one virtual machine (and class loader) at any time ....
Spring Application 구동시 JVM 안에 임베디드 모드 데이터 베이스가 실행된다. (휘발성)
https://www.h2database.com/html/features.html#connection_modes
Features
Features Feature List H2 in Use Connection Modes Database URL Overview Connecting to an Embedded (Local) Database In-Memory Databases Database Files Encryption Database File Locking Opening a Database Only if it Already Exists Closing a Database Ignore
www.h2database.com
4. h2 콘솔 접속 및 확인
http://localhost:포트번호/h2-console