
[ 쿼리문 ]
select id, title, content, user_id, (select count(id) from reply_tb where board_id = bt.id) reply_count from board_tb bt;
[ 뽑고자 하는 데이터 ]

[ BoardResponse ] - Count용 DTO 생성
@AllArgsConstructor
@Data
public class CountDTO {
private Integer id;
private String title;
private String content;
private Integer userId;
private Long replyCount;
}
[ BoardJPARepository ] - BoardQueryRepository로 해도 될 듯

@Query("select new shop.mtcoding.blog.board.BoardResponse$CountDTO(b.id, b.title, b.content, b.user.id, (select count(r.id) from Reply r where r.board.id = b.id)) from Board b")
List<BoardResponse.CountDTO> findAllWithReplyCount();

$ 를 써줬다! $를 써줘야 돌아감!
[ 테스트 ]
@Test
public void findAllWithReplyCount_test(){
// given
// when
List<BoardResponse.CountDTO> boardCountDTOList = boardJPARepository.findAllWithReplyCount();
System.out.println(boardCountDTOList);
// then
}
Share article