inblog logo
|
codingb
    Spring

    DTO 바로 받기 $사용 (ORM으로 해결 안 될 경우) - 2

    coding S's avatar
    coding S
    Mar 24, 2024
    DTO 바로 받기 $사용 (ORM으로 해결 안 될 경우) - 2

    [ 쿼리문 ]

    select id, title, content, user_id, (select count(id) from reply_tb where board_id = bt.id) reply_count from board_tb bt;

    [ 뽑고자 하는 데이터 ]

    notion image
     

    [ 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로 해도 될 듯

    notion image
    @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();
    notion image
    💡
    $ 를 써줬다! $를 써줘야 돌아감!
     

    [ 테스트 ]

    @Test public void findAllWithReplyCount_test(){ // given // when List<BoardResponse.CountDTO> boardCountDTOList = boardJPARepository.findAllWithReplyCount(); System.out.println(boardCountDTOList); // then }
     
    Share article

    codingb

    RSS·Powered by Inblog