실전! 스프링 데이터 JPA

Ch06. 나머지 기능들 - Specifications (명세)

webmaster 2021. 12. 28. 13:21
728x90

스프링 데이터 JPA는 JPA Criteria를 활용해서 이 개념을 사용할 수 있도록 지원

술어(predicate)

  • 참 또는 거짓으로 평가
  • AND OR 같은 연산자로 조합해서 다양한 검색조건을 쉽게 생성(컴포지트 패턴)
  • 예) 검색 조건 하나하나
  • 스프링 데이터 JPA는 org.springframework.data.jpa.domain.Specification 클래스로 정의

명세 기능 사용 방법

JpaSpecificationExecutor 인터페이스 상속

//JpaSpecificationExecutor extends
public interface MemberRepository extends JpaRepository<Member,Long>,MemberRepositoryCustom,JpaSpecificationExecutor<Member> {

MemberSpec.class
Test

  • Specification을 구현하면 명세들을 조립할 수 있음. where() , and() , or() , not() 제공
  • findAll 을 보면 회원 이름 명세( username )와 팀 이름 명세( teamName )를 and 로 조합해서 검색 조건으로 사용
  • 명세를 정의하려면 Specification 인터페이스를 구현
  • 명세를 정의할 때는 toPredicate(...) 메서드만 구현하면 되는데 JPA Criteria의 Root , CriteriaQuery , CriteriaBuilder 클래스를 파라미터 제공
  • 예제에서는 편의상 람다를 사용

참고

실무에서는 JPA Criteria를 거의 안 쓴다! 대신에 QueryDSL을 사용하자.

728x90