Book/스프링부트 핵심가이드

JPA Repository 인터페이스 생성과 사용 방법

블로그 주인장 2023. 11. 2.

리포지토리 인터페이스 설계

Spring Data JPA는 JpaRepository를 기반으로 더욱 쉽게 데이터베이스를 사용할 수 있는 아키텍처를 제공한다.

스프링부트로 JpaRepository를 상속하는 인터페이스를 생성하는 방법과 활용하는 방법을 알아보겠습니다.


리포지토리 인터페이스 생성


  • 리포지토리(Repository)는 Spring Data JPA가 제공하는 인터페이스이다.
  • 리포지토리는 엔티티가 생성한 데이터베이스에 접근하는데에 사용한다.
package com.springboot.jpa.data.repository;

import com.springboot.jpa.data.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
  • ProductRepository가 JpaRepository를 상속받을 때는 대상 엔티티와 기본값 타입을 지정해야한다.
  • 대상 엔티티를 Product로 설정하고 해당 엔티티의 @Id 필드 타입인 Long을 설정하면 된다.

 

JPARepository에서 제공하는 기본 메서드

@NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
    List<T> findAll();

    List<T> findAll(Sort sort);

    List<T> findAllById(Iterable<ID> ids);

    <S extends T> List<S> saveAll(Iterable<S> entities);

    void flush();

    <S extends T> S saveAndFlush(S entity);

    <S extends T> List<S> saveAllAndFlush(Iterable<S> entities);
    
    
    //생략...
}

 

리포지토리 메서드의 생성 규칙


  • CRUD(Create, Read, Update, Delete)에서 따로 생성해서 사용하는 메서드는 대부분 Read(Select) 부분이다.
  • 리포지토리에서 기본적으로 제공하는 조회 메서드는 기본값으로 단일 조회하거나 전체 엔티티를 조회하는 것만 지원하고 있어서 다른 조회 메서드가 필요하다.

 

조회 메서드(find) 조건으로 붙일 수 있는 기능

  1. FindBy
    • SQL문의 where 절 역할을 수행하는 구문이다. findBy 뒤에 엔티티의 필드값을 입력해서 사용한다.
    • ex) findByName(String name)
  2. AND,OR
    • 조건을 여러 개 설정하기 위해 사용한다.
    • findByNameAndEmail(String name, String email)
  3. Like/NotLike
    • SQL문의 like와 동일한 기능을 수행하며, 특정 문자를 포함하는지 여부를 조건으로 추가한다.
    • 비슷한 키워드로 Containing, Contains, isContaing
  4. StartsWith/StartingWith
    • 특정 키워드로 시작하는 문자열 조건을 설정한다.
  5. EndsWith/EndingWith
    • 특정 키워드로 끝나는 문자열 조건을 설정한다.
  6. IsNull/IsNotNull
    • 레코드 값이 Null 이거나 Null이 아닌 값을 검색한다.
  7. True/False
    • Boolean 타입의 레코드를 검색할 때 사용한다.
  8. Before/After
    • 시간을 기준으로 값을 검색한다.
  9. LessThan/GreaterThan
    • 특정 값(숫자)을 기준으로 대/소 비교를 할 때 사용한다.
  10. Between
    • 두 값(숫자) 사이의 데이터를 조회한다.
  11. OrderBy
    • SQL문에서 order by 와 동일한 기능을 수행한다.
    • ex) 가격 순으로 이름 조회를 수행 -> List<Product> findByNameOrderByPriceAsc(String name); 
  12. countBy
    • SQL문의 count와 동일한 기능을 수행하며, 결과값의 개수(count)를 추출한다.
반응형

댓글