Framework/Spring

[Spring] H2 서버 연결하기

IT수정 2024. 10. 30. 12:57

H2

H2는 Java로 작성된 경량의 관계형 데이터베이스 관리 시스템이다. 주로 개발과 테스트 환경에서 사용되며, 메모리 내에서 작동할 수 있고, 파일 기반 저장소도 지원한다. H2는 빠르고, 설치가 간편하며, SQL 표준을 지원하는 특징이 있다.

 

H2 설치

다음 링크를 통해 H2를 설치한다.

https://www.h2database.com/html/download-archive.html

 

bin 폴더의 h2.bat을 실행한다.

 

JDBC URL을 입력해서 DB를 생성해 연결해 준다.

jdbc:h2:~/DB이름 : DB이름으로 새로운 DB 생성
jdbc:h2:tcp://localhost/~/DB이름 : 기존의 DB이름에 연결

 

정상적으로 연결되면 다음과 같이 표시된다.

 

Spring에서 H2 사용하기

application.properties에 다음 코드를 추가한다.

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:tcp://localhost/~/testapi
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

 

혹은 application.yml 파일을 생성해서 다음 코드를 작성한다.

yml 확장자는 가독성이 properties보다 뛰어나다.

spring:
  application:
    name: hello2-spring
  h2:
    console:
      enabled: true
  datasource:
    url: jdbc:h2:tcp://localhost/~/testapi
    driver-class-name: org.h2.Driver
    username: sa
    password:

 

단, 환경설정 파일은 한 개 이상 존재할 수 없으므로 둘 중에 하나만 생성하도록 한다.

 

최종 환경설정

spring:
  application:
    name: hellov2-spring
  datasource:
    url: jdbc:h2:tcp://localhost/~/testApi
    driver-class-name: org.h2.Driver
    username: sa
  jpa:
    hibernate:
      ddl-auto: create    #update
    properties:
      hibernate:
        format_sql: true
  thymeleaf:
    prefix: classpath:/templates/ #접두어
    suffix: .html #접미어

logging:
  level:
    org.hibernate.SQL: debug #생성한 SQL이 로그를 통하여 찍어준다.
    org.hibernate.orm.jdbc.bind: trace #스프링 부트 3.x hibernate6

'Framework > Spring' 카테고리의 다른 글

[Spring] HTML 구성 요소의 통합  (2) 2024.10.31
[Spring] 회원 관리 예제  (1) 2024.10.31
[Spring] MVC 패턴  (0) 2024.10.30
[Spring] IntelliJ IDEA 설정  (0) 2024.10.29
[Spring] 기본 환경 설정  (1) 2024.10.29