Spring Boot와 H2 연동하기

Tina Jeong·2020년 8월 22일
3

H2 데이터베이스는 가볍고 연동이 간편해서 개인프로젝트 시 많이 사용된다.
H2는 JVM 위에 올라가는게 default여서 어플리케이션 재구동시 DB가 다 날라가며, 외부 접근도 불가하다. 이제까지는 인메모리로 쓰다가 IntelliJ DB Client💕 를 사용하려고 server 모드로 세팅을 해보았다. Local mode, Server mode 두 가지 방법 모두 정리했다.

Local Mode로 연동

메모리 디비로 설정하면 @Configuration 어노테이션이 포함된 클래스를 따로 설정하지 않아도 된다.
아래와 같이 세팅해주니, 어플리케이션 실행 중에
http://localhost:8080/h2-console/의 경로로 콘솔 접근이 가능했다. path 옵션을 통해 h2 console의 경로를 변경할 수도 있다.

application.yaml

spring:
  h2:
    console:
      enabled: true
  profiles:
    active: local
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:userdb;DB_CLOSE_DELAY=-1
    username: sa
    password: 

그러나, 앞서 언급했듯 메모리 디비(H2 embedded는 JVM 위에서 돌아감)라서 어플리케이션을 실행할 때마다 테이블이 날라간다. 영속적인 사용을 위해선 server mode로 세팅을 해야한다.

Server Mode로 연동

local 모드로 실행하면 외부 접근이 불가하다. 그러므로 외부에서 접근하려면 server 모드(tcp로 우회하기)로 세팅을 해주어야 한다.
local 세팅과 다른 점은 hikari 하위 부분에 jdbc-url을 적어주어야 에러가 나지 않는다.

application.yaml

spring:
  h2:
    console:
      enabled: true
  profiles:
    active: local
  datasource:
    hikari:
      jdbc-url: jdbc:h2:./data/testdb
      # 또는 jdbc:h2:tcp://localhost:9092/./data/testdb
      driver-class-name: org.h2.Driver
      username: sa
      password:

Server Configuration 클래스 작성

@Configuration
@Profile("local")
public class H2ServerConfiguration {

    @Bean
    @ConfigurationProperties("spring.datasource.hikari")
    public DataSource dataSource() throws SQLException {
        Server server = defaultRun();
        return new HikariDataSource();
    }

    private Server defaultRun() throws SQLException {
        return Server.createTcpServer(
                "-tcp",
                "-tcpAllowOthers",
                "-ifNotExists",
                "-tcpPort", 9092 + "").start();
    }
}

요약

  • 🔌 Local Mode : 인메모리, 설정 간편, 외부 접근 불가
  • 🗄 Server Mode : 영속사용 ,추가 설정 필요, 외부 접근 가능

참고

https://dico.me/java/articles/241
https://www.h2database.com/html/tutorial.html

profile
Keep exploring, 계속 탐색하세요.

0개의 댓글