본문 바로가기
[SpringBoot]/[Spring 강의]

[Kotlin + Spring] QueryDSL 사용해보기

by Hevton 2024. 4. 8.
반응형

 

이전 글을 통한 세팅에 이어서 QueryDSL을 활용해보겠습니다.

 

 

Post 테이블과 1: N 관계로, UserLiked와 Comment가 있습니다.

저는 Post를 가져올 때 UserLiked의 갯수와 Comment의 갯수를 함께 가져오는 작업을 QueryDSL로 진행해보겠습니다.

 

data class PostWithCountsDTO(
    val id: Long,
    val title: String,
    val type: String,
    val subType: String,
    val content: String,
    val time: Long,
    val hasImage: Boolean,
    val commentCount: Long,
    val likedUsersCount: Long
)

 

DTO Projection을 위해서 DTO를 정의해주고

interface PostSupport {
    fun findPostsWithCounts(): List<PostWithCountsDTO>
}

 

기존의 PostRepository에서 활용해주기 위한 Support 인터페이스를 정의한 뒤에

PostSupportImpl을 구현해줍니다

@Component
class PostSupportImpl(
    private val queryFactory: JPAQueryFactory, // JPAQueryFactory를 주입받아 사용한다.
) : PostSupport {
    override fun findPostsWithCounts(): List<PostWithCountsDTO> {
        val post = QPost.post
        val comment = QComment.comment
        val userLike = QUserLike.userLike

        return queryFactory
            .select(
                Projections.constructor(
                    PostWithCountsDTO::class.java,
                    post.id,
                    post.title,
                    post.type,
                    post.subType,
                    post.content,
                    post.time,
                    post.hasImage,
                    comment.id.countDistinct(),
                    userLike.id.countDistinct(),
                ),
            )
            .from(post)
            .leftJoin(post.comments, comment)
            .leftJoin(post.likedUsers, userLike)
            .groupBy(post.id)
            .fetch()
    }
}

 

 

그리고 기존의 PostRepository에서 PostSupport를 구현한다고 선언만 해주면

interface PostRepository : JpaRepository<Post, Long>, PostSupport

 

이후 Servce에서 postRepository를 활용해서 함수를 그냥 사용할 수 있게 됩니다!

 

 

틀린 내용 지적 부탁드립니다! 더 알게되면 수정하겠습니다.

 

참고

- https://velog.io/@beinte0419/Spring-Boot-JPA-with-Kotlin-Querydsl-%EC%84%A4%EC%A0%95-%EB%B0%8F-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0

- https://h-kkaemi.tistory.com/23

- https://keylog.tistory.com/entry/Querydsl-%ED%94%84%EB%A1%9C%EC%A0%9D%EC%85%98

 

 

 

 

 

 

반응형