개발/spring
[h2] h2를 기본 데이터베이스로 사용하기
방푸린
2024. 1. 15. 17:08
반응형
환경: springboot2.7, java 17, maven
h2를 내장하는 테스트 프로젝트 생성
아래와 같이 설정했다고 가정
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>runtime</scope> # <-- 기본이 test 로 되어 있고, 이러면 프로젝트에서 사용할 수 없음
</dependency>
spring:
h2:
console:
enabled: true
settings:
web-allow-others: true
path: /h2-console // H2 콘솔 사용한다는 뜻
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:test //db 연결 후 테이블 자동 생성
하지만 서버가 뜨고 db 연결 시 아래와 같은 에러 발생
testdb 데이터베이스를 springboot실행 시 자동 생성해주어야 하는데 그렇지 못함.
H2 1.4.198 이후 버전부터는 보안 문제로 자동으로 디비를 생성하지 않음.
h2 버전의 문제로 1.4 -> 1.3.176으로 낮추면 해결됨
((최신 버전으로 해도 그러는지 확인 필요))
h2를 메인으로 쓰면서, 서비스 시작 시 entity 테이블을 자동으로 생성하고자 하는 경우
application.yml에 아래처럼 작
spring:
h2:
console:
enabled: true
settings:
web-allow-others: true
path: /h2-console
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:test
jpa:
defer-datasource-initialization: true ###
hibernate:
ddl-auto: create-drop
show-sql: true
generate-ddl: true
springboot 2.5 이상에서는 위처럼 defer-datasource-initialization 값을 추가해야 한다.
Spring Boot 2.5 Release Notes
Spring Boot. Contribute to spring-projects/spring-boot development by creating an account on GitHub.
github.com
+ 초기 데이터까지 넣어야 한다면
/resources 경로에 data.sql 파일로 쿼리를 넣으면, entity 생성 후 자동 실행한다.
728x90
반응형