자바/스프링

스프링부트 H2 데이터베이스 설정 방법

땅부자몽구스 2021. 10. 4. 14:51

1. build.gradle에 아래와 같이 의존성을 추가한다.

# build.gradle
...
dependencies {
	...
	runtimeOnly 'com.h2database:h2'
	...
}
...

maven의 경우 아래와 같이 의존성을 추가한다.

# pom.xml
...
<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>
...

 

2. PropertySource(application.properties 등)에 아래와 같이 설정을 추가한다.

# application.properties
...
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=user
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

spring.h2.console.enabled=true

spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.format_sql=true

logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.type.descriptor.sql=trace
...
  • spring.datasource.url

H2로 접속할 수 있는 URL이다.

"jdbc:h2:mem:test"의 의미는 메모리에서 "test"라는 데이터베이스에 접속하겠다는 의미이다.

(출처: http://www.h2database.com/html/features.html#connection_modes)

 

파일로 데이터베이스를 관리하는 경우에는 아래와 같이 설정할 수 있다.

spring.datasource.url=jdbc:h2:file:~/test

파일의 경로가 "~/test"이므로 Windows의 경우 "C:\Users\사용자" 경로에 저장된다.

만약 "jdbc:h2:file:./test"와 같이 설정하면, 현재 프로젝트 루트 경로에 "test.mv.db" 등의 데이터베이스 파일이 생성된다.

(출처: http://www.h2database.com/html/features.html#database_file_layout)

 

  • spring.datasource.나머지

사용자, 비밀번호, 드라이버 정보이다.

사용자와 비밀번호는 임의로 지정하면 된다.

드라이버 클래스는 H2 드라이버 클래스로 설정해야 한다.

 

  • spring.h2.console.enabled

"true"로 설정해야 H2 콘솔을 사용할 수 있다.

콘솔 접속 경로: 서버주소/h2-console

 

Spring Security를 사용하는 경우 WebSecurity configure() 메서드에서

콘솔 접속 요청 경로에 대해 아래와 같이 ignoring() 설정을 해야 정상적으로 이용할 수 있다.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
		...

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers(
                        "/error"
                        , "/favicon"
                        ...
                        , "/h2-console/**"
                );
    }

		...
}

 

  • spring.jpa.hibernate.ddl-auto

Hibernate 초기화 전략에 대한 설정이다. 기본값은 "none"으로 아무것도 실행하지 않는다.

"create"는 어플리케이션 실행 시점에 Entity 클래스에 매핑되는 테이블을 drop 후 재생성한다.

이는 테스트 목적의 DB를 사용할 때 적절한 Hibernate 전략이다.