Spring Data JPA 사용하기

Sungbum Park·2021년 2월 16일
0

Sping Boot 2.4 버전에서 Spring Data JPA를 사용해보자.

0. 개발환경


  • Spring Boot 2.4
  • OpenJDK 11
  • Gradle 4.9
  • H2 (테스트 환경)

1. Spring Data JPA 시작하기


1.1. Gradle 의존성 추가

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

1.2. 정상 동작 테스트

위 의존성을 추가하고, 내 프로젝트에서 Spring Data JPA를 정상적으로 사용할 수 있는지 테스트해보자. 테스트 예제는 스프링 공식 문서인 해당 링크를 참고하였다.

@DataJpaTest
public class CustomerRepositoryTest {

    @Autowired private CustomerRepository customerRepository;

    @Test
    @DisplayName("findById 기본 테스트 + Spring Data JPA 동작하는지 테스트")
    void findById() {
        Customer customer = new Customer("sungbum", "park");
        customerRepository.save(customer);

        Customer foundCustomer = customerRepository.findById(1L);

        assertThat(foundCustomer).isEqualTo(customer);
    }
}

현재 버전에서는 간단히 @DataJpaTest 만 추가해주면 되었다. 이 애노테이션의 내부를 살펴보면 다음과 같다.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(DataJpaTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
@OverrideAutoConfiguration(enabled = false)
@TypeExcludeFilters(DataJpaTypeExcludeFilter.class)
@Transactional
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration
public @interface DataJpaTest {
	// ...
}
  • @ExtendWith(SpringExtention.class): 해당 애노테이션은 JUnit5에서 테스트를 위한 스프링 컨테스트를 올린다.
  • @AutoConfigureTeestDatabase: 기본적으로 H2 데이터베이스를 사용한다.

이 외의 애노테이션은 필요할 때 조금씩 정리할 예정이다.

2. H2 데이터베이스 사용하기


데이터베이스 관련 테스트는 크기가 작고 메모리를 사용하여 빠르게 동작하는 인메모리 데이터베이스를 사용하는 것이 좋다. 그 중에서도 H2 데이터베이스를 가장 많이 사용한다. 테스트를 위해 H2 데이터베이스의 사용법을 간단히 살펴보자.

2.1. application.yml 파일 설정

spring:
  datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    username: sa
    password:
  h2:
    console:
      enabled: true
      path: /h2-console
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        format_sql: true
        show_sql: true
        use_sql_comments: true

위 설정 후 서버를 실행하면, localhost:8080/h2-console 로 h2 데이터베이스 콘솔에 접속할 수 있다. 그 후 위에서 설정한 url, username, password를 입력하여 접속하면 더 편하게 데이터이스를 테스트할 수 있다.

참고자료


0개의 댓글