개발을 잘하고 싶은 개발자

[Spring JPA] Specification으로 쿼리 조건 처리하기 본문

카테고리 없음

[Spring JPA] Specification으로 쿼리 조건 처리하기

_소피아 2022. 1. 16. 15:23

JPA를 사용하면서 까다로운 쿼리를 처리하는데 종종 어려움이 있다.

이 때 "Specification"의 도움을 받아 동적쿼리(Dynamic Query)로 처리할 수 있다

참고 페이지

https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

https://dahye-jeong.gitbook.io/spring/spring/2020-04-12-jpa-specification

  1. JpaSpecificationExecutor을 extends 해준다.

Specification을 입력 받도록 Repository 인터페이스 정의하기

public interface PostRepository 
					extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {
}
  1. 검색 조건을 모아 놓은 클래스 만들기 (Specifications 객체)
public class PostSpecs {
    public static Specification<Post> withTitle(String title) {
        return (Specification<Post>) ((root, query, builder) -> 
                builder.equal(root.get("title"), title)
        );
    }
}
  1. 검색 조건을 조합한 Specification 인스턴스를 이용해서 검색하기
@GetMapping("/post/list")
    public List<Post> getPostList(@RequestParam(required = false) String title,
                                  @RequestParam(required = false) String tag,
                                  @RequestParam(required = false) Integer likes) {
        if (title != null) {
            return postRepository.findAll(PostSpecs.withTitle(title));
        } else if (...) {
            ...
        }
    }

간단해보이지만 어렵고

생각보다 엄청 많은 기능을 제공하기 때문에 더 공부하고 실제 소스에 녹여봐야 내것이 될 것 같다.

이 Specification을 몰랐을 때에는 귀찮고, 쉬운 길을 찾아 직접 @Query 어노테이션을 사용해서 쿼리를 작성했었다.

이제는 특수한 상황을 제외하고는 되도록 Specification을 사용하는 습관을 들여봐야겠다.