Java/Spring Boot

Spring boot H2 DB 설정

요술공주밍키 2022. 11. 10. 14:16

Spring boot에서 DB를 무엇을 사용할까 고민하다 가장 간단한 방법인 H2 DB를 연동하였다.

 

우선 build.gradle에서 dependency를 설정해야 한다.

dependency 설정

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'com.h2database:h2:1.4.200'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

저는 h2 버전을 1.4.200으로 사용하였다. 버전을 신경 쓰지 않는다면 그냥 h2까지만 적어도 무방.

 

dependency를 설정했다면 이제 프로퍼티를 설정하면 된다.

application.properties 설정

# h2 DB 사용관련
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

# h2 DB 기능설정
spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# 테이블이 없을 때 생성할 수 있도록 설정
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop

 

spring.datasource.url을 보면 jdbc:h2:~/test라고 되어 있는데 저 방식은 메모리 방식이 아닌

File로 저장하는 방식이고 메모리 혹은 다른 방식으로 사용하고 싶으신 분들은 구글에 검색해서

url 부분만 변경하면 된다.

 

Test

localhost에 접속하신 뒤 Properties에서 설정한 Path 값을 입력하면 http://localhost:8080/h2-console

h2-console

위와 같이 Console 창이 뜨고 중간에 파란 글씨로 써있는 URL에 본인이 선택한 방식의 URL을 입력하면 된다.

 

h2 DB 페이지

그럼 위와 같은 결과를 얻게 된다. 옆에 MEMBER 테이블은 원래 없는게 정상이다.