[JPA] Specification을 통한 검색 구현

김나영·2023년 7월 4일
0

SPRING

목록 보기
7/11

Specification

검색 조건을 생성하는 인터페이스.

  • Criteria를 이용해서 검색 조건을 생성한다.

    Creiteria

==> specification의 return 타입이 Predicate!

파라미터 인자는
검색조건을 생성할때 사용하는 root, criteriaBuilder가 존재

Repository에서 Specification사용

specification을 이용하여 검색 조건을 지정해준다.

List<T> findAll(Specification<T> spec)

spec 인터페이스를 구현한 클래스를 계속 만드는 것은 비효율적이기 때문에
람다식을 이용해서 spec을 생성한다!

public static Specification<ProductEntity> nameLike(String value){
        return (root, query, builder) -> builder.like(root.get("name"), "%" + value + "%");
}
ProductNameSpecification spec = ProductSpecification.nameLike("이름");
List<ProductEntity> prod = productRepository.findAll(spec);
  • OR / AND를 이용해서 조합 가능하다!
  • WHERE을 사용한 선택적 조합

    먼저 where null 을 주면 빈 조건인 spec을 return함
    --> 이후 조건을 주면서 spec들을 조합해서 최종 spec을 findAll에 전달

Specification + 페이징, 정렬

List<T> findAll(Specification<T> spec, Sort s)
Page<T> findAll(Specification<T> spec, Pageable pageable)
List<T> findAll(Specification<T> spec, Pageable pageable)
profile
응애 나 애기 개발자

0개의 댓글