[Spring] 스프링 DB 2편 5-4. JPA 설정

강우엉·2023년 8월 31일

Spring

목록 보기
317/359

spring-boot-starter-data-jpa 라이브러리를 사용하면 JPA와 스프링 데이터 JPA를 스프링 부트와 통합하고, 설정도 아주 간단히 할 수 있다.
spring-boot-starter-data-jpa 라이브러리를 사용해서 간단히 설정하는 방법을 알아보자.

build.gradle 에 다음 의존 관계를 추가한다.

//JPA, 스프링 데이터 JPA 추가
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

build.gradle 에 다음 의존 관계를 제거한다.

//JdbcTemplate 추가
//implementation 'org.springframework.boot:spring-boot-starter-jdbc'

spring-boot-starter-data-jpa 는 spring-boot-starter-jdbc 도 함께 포함(의존)한다. 따라서 해당 라이브러리 의존관계를 제거해도 된다. 참고로 mybatis-spring-boot-starter 도 spring-bootstarter-jdbc 를 포함하기 때문에 제거해도 된다.

build.gradle - 의존관계 전체

plugins {
    id 'org.springframework.boot' version '2.6.5'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'

    //JdbcTemplate 추가
//    implementation 'org.springframework.boot:spring-boot-starter-jdbc'

    //MyBatis 추가
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.0'

    //JPA, 스프링 데이터 JPA 추가
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

	//H2 데이터베이스 추가
    runtimeOnly 'com.h2database:h2'

    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    //테스트에서 lombok 사용
    testCompileOnly 'org.projectlombok:lombok'
    testAnnotationProcessor 'org.projectlombok:lombok'
}

tasks.named('test') {
    useJUnitPlatform()
}

다음과 같은 라이브러리가 추가된다.

  • hibernate-core : JPA 구현체인 하이버네이트 라이브러리
  • jakarta.persistence-api : JPA 인터페이스
  • spring-data-jpa : 스프링 데이터 JPA 라이브러리

application.properties 에 다음 설정을 추가하자.
main, test 2곳 모두 추가해야한다.

#JPA log
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
  • org.hibernate.SQL=DEBUG : 하이버네이트가 생성하고 실행하는 SQL을 확인할 수 있다.
  • org.hibernate.type.descriptor.sql.BasicBinder=TRACE : SQL에 바인딩 되는 파라미터를 확인할 수 있다.
  • spring.jpa.show-sql=true : 참고로 이런 설정도 있다. 이전 설정은 logger 를 통해서 SQL이 출력된다. 이 설정은 System.out 콘솔을 통해서 SQL이 출력된다. 따라서 이 설정은 권장하지는 않는다.
    (둘다 켜면 logger , System.out 둘다 로그가 출력되어서 같은 로그가 중복해서 출력된다.)
profile
우엉이의 코딩 성장일기💻

0개의 댓글