Search
Duplicate

[스프링 게시판] 댓글 개수 표시

@3/21/2023

하이버네이트 select 서브 쿼리 이용

PostListDTO
@AllArgsConstructor @Getter @Setter public class PostListDTO { private Long postId; private String title; private String userName; private LocalDateTime regDate; private Integer view; private String formattedRegDate; private Long commentsCount; ... }
Java
복사
PostRepository
public List<PostListDTO> findAll(int offset, int limit, PostSearchDTO postSearchDTO) { String jpql = "select new dev.gyuray.forum.repository.post.PostListDTO(" + "p.id, " + "p.title, " + "u.name, " + "p.regDate, " + "p.view, " + "'', " + "(select count(*) from Comment c where c.post = p)" + ") " + "from Post p " + "join p.user u "; ... }
Java
복사
하이버네이트에서 지원하는 select 서브쿼리를 통해 댓글 개수를 받아와 DTO에 넣음
View
<!-- 게시글 --> <tbody class="table-group-divider"> <tr th:each="postListDTO : ${postListDTOs}" class="text-center h-2"> <td th:text="${postListDTO.postId}">2</td> <td class="text-dark text-start"> <a class="list-group-item d-inline me-3" th:text="${postListDTO.title}" th:href="@{/posts/{postId}?currentPage={currentPage} (postId = ${postListDTO.postId}, currentPage = ${postPagerDTO.currentPage})}"> 글제목 </a> <i class="bi bi-chat-left-text text-secondary" style="font-size:13px;" th:text="|&nbsp;${postListDTO.commentsCount}|"></i> </td> <td th:text="${postListDTO.userName}">운영자</td> <td th:text="${postListDTO.view}">1</td> <td th:text="${postListDTO.formattedRegDate}">2023-03-01 12:34:56</td> </tr> <tr th:if="${postListDTOs.size() == 0}" class="text-center h-2"> <td colspan="5">게시글이 없습니다.</td> </tr> </tbody>
Java
복사

실제 전송 쿼리

select post0_.post_id as col_0_0_, post0_.title as col_1_0_, user1_.user_name as col_2_0_, post0_.reg_date as col_3_0_, post0_.view as col_4_0_, '' as col_5_0_, ( select count(*) from comment comment2_ where comment2_.post_id=post0_.post_id ) as col_6_0_ from post post0_ inner join user user1_ on post0_.user_id=user1_.user_id order by post0_.post_id desc limit 10;
SQL
복사

결과 화면

관련 커밋

b556b3934f9e98dc5d63912aa7b8880690bae747
commit