Specification는 검색조건을 추상화한 객체다. 검색 조건에 대해 Specification에 생성하고, 이를 통해 다양한 조건의 검색을 할 수 있다는 뜻이다.
Spring JPA Specificatoin은 동적 쿼리(Dynamic Query)를 작성할 때 도움이 된다. 예를 들어, 필터링(해당 값이 있는 경우에만 조건을 걸 때)을 할때 사용하면 좋다.
Specification 다음과 같은 방식으로 조건 검색을 한다.
Specification을 입력 받도록 Repository 인터페이스 정의하기
검색 조건을 모아 놓은 클래스 만들기 (Specifications 객체)
검색 조건을 조합한 Specification 인스턴스를 이용해서 검색하기
public interface PaymentRepository extends JpaRepository<Payment, String>, JpaSpecificationExecutor<Payment>{
}
상속받지 않고 필요한 메소드만 직접 정의해서 구현해도 된다. JpaSpecificationExecutor를 살펴보면 다음과 같이 구현되어 있는 것을 볼 수 있다.
/**
* Interface to allow execution of {@link Specification}s based on the JPA criteria API.
*
* @author Oliver Gierke
* @author Christoph Strobl
*/
public interface JpaSpecificationExecutor<T> {
/**
* Returns a single entity matching the given {@link Specification} or {@link Optional#empty()} if none found.
*
* @param spec can be {@literal null}.
* @return never {@literal null}.
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException if more than one entity found.
*/
Optional<T> findOne(@Nullable Specification<T> spec);
/**
* Returns all entities matching the given {@link Specification}.
*
* @param spec can be {@literal null}.
* @return never {@literal null}.
*/
List<T> findAll(@Nullable Specification<T> spec);
/**
* Returns a {@link Page} of entities matching the given {@link Specification}.
*
* @param spec can be {@literal null}.
* @param pageable must not be {@literal null}.
* @return never {@literal null}.
*/
Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);
/**
* Returns all entities matching the given {@link Specification} and {@link Sort}.
*
* @param spec can be {@literal null}.
* @param sort must not be {@literal null}.
* @return never {@literal null}.
*/
List<T> findAll(@Nullable Specification<T> spec, Sort sort);
/**
* Returns the number of instances that the given {@link Specification} will return.
*
* @param spec the {@link Specification} to count instances for. Can be {@literal null}.
* @return the number of instances.
*/
long count(@Nullable Specification<T> spec);
}
JPA Criteria
JPA Criteria는 동적 쿼리를 사용하기 위한 JPA 라이브러리이다. 기본적으로 JPQL(JPA Query Language)과 같이 엔티티 조회를 기본으로 하며, 컴파일 시점에 에러를 확인할 수 있는 장점이 있다.