728x90
- the BaseJpaRepository from the Hypersistence Utils project, which is a better alternative to the default JpaRepository from Spring Data
- the JpaSpecificationExecutor, which provides the Spring Data Specification filtering methods
가져와야하는 검색 Specification 을 미리 인터페이스화 한다
@Repository
public interface PostCommentRepository
extends BaseJpaRepository<PostComment, Long>,
JpaSpecificationExecutor<PostComment> {
interface Specs {
static Specification<PostComment> byPost(Post post) {
return (root, query, builder) ->
builder.equal(root.get(PostComment_.post), post);
}
static Specification<PostComment> byStatus(PostComment.Status status) {
return (root, query, builder) ->
builder.equal(root.get(PostComment_.status), status);
}
static Specification<PostComment> byReviewLike(String reviewPattern) {
return (root, query, builder) ->
builder.like(root.get(PostComment_.review), reviewPattern);
}
static Specification<PostComment> byVotesGreaterThanEqual(int votes) {
return (root, query, builder) ->
builder.greaterThanOrEqualTo(root.get(PostComment_.votes), votes);
}
static Specification<PostComment> orderByCreatedOn(
Specification<PostComment> spec) {
return (root, query, builder) -> {
query.orderBy(builder.asc(root.get(PostComment_.createdOn)));
return spec.toPredicate(root, query, builder);
};
}
}
}
Adding an ORDER BY clause to the Spring Data JPA Specification
ORDER BY 값 넣기
List<PostComment> comments = postCommentRepository.findAll(
orderByCreatedOn(
byPost(post)
)
);
Combining multiple Spring Data JPA Specifications
List<PostComment> comments = postCommentRepository.findAll(
orderByCreatedOn(
byPost(post)
.and(byStatus(PostComment.Status.PENDING))
.and(byReviewLike(reviewPattern))
.and(byVotesGreaterThanEqual(minVotes))
)
);
728x90
'Spring 정리ver2 > Data + JPA' 카테고리의 다른 글
언젠가 JPA로 돌아가면 쓸 것 (1) | 2023.11.28 |
---|