본문 바로가기

Spring/JPA & Hibernate

Spring Data JPA - H2 연동

반응형

Spring Boot Starer 애플리케이션으로 H2 데이터베이스 연동하는 방법

스프링 부트의 경우, persistence.xml 으로 설정을 하지 않아도 된다.

Spring boot 의 auto configuration 기능으로 자동 설정을 해주기 때문이다.

 

단지, main/resources/application.yml 파일에 datasource 관련 정보만 세팅 해주면 된다.


spring:
  datasource:
    url: jdbc:h2:tcp://localhost/~/store
    username: sa
    password:
    driver-class-name: org.h2.Driver
  jpa:
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        #        show_sql: true
        format_sql: true
logging:
  level:
    org.hibernate.SQL: debug
    org.hibernate.type: trace

hibernate의 show_sql : 옵션은 System.out 에 하이버네이트 실행 SQL을 출력한다.
이 보다는 로거를 통해 SQL을 출력하는 org.hibernate.SQL 옵션을 키는 것이 바람직하다.

 

하지만, 하이버네이트 SQL 로그느 쿼리 파라미터 값까지 남겨주진 않는다.

이에 대한 불편함을 느낀다면, 외부 라이브러리 spring-boot-data-source-decorator 를 통해 해결할 수 있다.

 

spring-boot-data-source-decorator 에서는 4가지를 제공한다.

  • P6Spy - adds ability to intercept and log sql queries, including interception of a most Connection, Statement and ResultSet methods invocations
  • Datasource Proxy - adds ability to intercept all queries and Connection, Statement and ResultSet method calls
  • FlexyPool - adds connection pool metrics (jmx, codahale, dropwizard) and flexible strategies for adjusting pool size on demand
  • Spring Cloud Sleuth - library for distributed tracing, if found in classpath enables jdbc connections and queries tracing (only with p6spy or datasource-proxy)

라이브러리 추가

 

  • Gradel
implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:${version}'

 

  • Maven

<dependency>
    <groupId>com.github.gavlyukovskiy</groupId>
    <artifactId>p6spy-spring-boot-starter</artifactId>
    <version>${version}</version>
</dependency>

반응형

'Spring > JPA & Hibernate' 카테고리의 다른 글

트랜잭션  (0) 2021.01.05
Spring Boot JPA 활용1  (0) 2020.12.26
JPQL(Java Persistence Query Language) - 2  (0) 2020.12.22
JPQL(Java Persistence Query Language) - 1  (0) 2020.12.20
JPA 쿼리  (0) 2020.12.20