Spring Data JPA를 사용할 때, 데이터 베이스 쿼리를 생성하기 위한 방법은 크게 3가지가 존재한다
@Query 어노테이션의 사용findById(id))public interface PostCommentRepository extends JpaRepository<PostComment, Long>, JpaSpecificationExecutor<PostComment> {
// 다른 리포지토리 메서드들...
}
public class PostCommentSpecification {
public static Specification<PostComment> hasPostId(Long postId) {
return (root, query, cb) -> cb.equal(root.get("post").get("id"), postId);
}
public static Specification<PostComment> isTopLevelComment() {
return (root, query, cb) -> cb.isNull(root.get("parentComment"));
}
// 추가 Specifications...
}
// 서비스 레이어
List<PostComment> comments = postCommentRepository.findAll(
where(hasPostId(postId)).and(isTopLevelComment())
);
@Query 어노테이션public interface PostCommentRepository extends JpaRepository<PostComment, Long>, JpaSpecificationExecutor<PostComment> {
@Query("SELECT pc.parentComment.commentId, COUNT(pc) " +
"FROM PostComment pc " +
"WHERE pc.post.postId = :postId AND pc.parentComment IS NOT NULL " +
"GROUP BY pc.commentId")
List<Object[]> countRepliesByPostId(@Param("postId") Long postId);
}
public interface PostCommentRepository extends JpaRepository<PostComment, Long>, JpaSpecificationExecutor<PostComment> {
List<PostComment> findByPostIdAndParentCommentIsNull(Long postId);
}

이전 포스팅 에서 JPA specification에 대해서 처음 다루어 보았는데, 어떤 상황에 어떤 방법을 사용하면 좋을지를 정리하고 싶어 위 포스팅을 작성하였다✏️✏️ 무조건 specification이나 @Query를 사용하지 말고, 필요한 상황에만 쓸 수 있도록 해야겠다 !!
좋은 정리네요!