inblog logo
|
codingb
    Spring

    DTO 바로 받기 (ORM으로 해결 안 될 경우) - 1

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

    [ 조회를 하는데 DTO로 바로 받는 것 ]

     

     
    notion image
    id, title, content 하고나서, 게시글에 있는 댓글 갯수(카운트)를 뽑아야할 경우가 있다.
    notion image
    이런식으로 나오게끔 뽑아보자!! 근데 이렇게 생긴 엔티티가 없지않나? 4자리(board_id 자리)에 서브쿼리가 들어가야한다. 이런 결과가 나오는 쿼리는 아래에.
    select id, title, content, user_id, (select count(id) from reply_tb where board_id = bt.id) reply_count from board_tb bt;
    where board_id = bt.id 현재 조회 중인 게시글의 ID와 reply_tb 테이블의 board_id가 일치하는 댓글만을 세라 그런데 엔티티로는 이런 데이터를 못받는다. QLRM 안쓰고, 이런걸 받을땐 네이티브쿼리나 오브젝트 배열로 받았잖아? JPQL은 간단하게 가능
     

    [ JPQL DTO ]

    notion image
    이렇게 count를 못 쓰기 때문에 이걸 받을 수 있는 DTO를 만들어준다
     

    [ BoardCountDTO ]

    notion image
    static 없어도 되는걸까?
     

    [ BoardJPARepository ] - JPARepository DTO 매핑하기

    @Query("select new shop.mtcoding.blog.board.BoardCountDTO(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<BoardCountDTO> findAllWithReplyCount();
    💡
    패키지명을 new로 가져오는데, 풀로 적어서 가져와야함!!
    BoardJPARepository는 return할 때 Board 타입밖에 안 됨. (UserJPARepository는 User 타입만 리턴하겠지...) JPARepository는 DTO 매핑이 되지 않는다! 그러나 이 문법을 적으면 DTO 매핑 가능!
     

    [ 테스트 하다가 ]

    notion image
    //return 값 = List<BoardCountDTO>

    [ 에러 ]

    notion image
    notion image
    생성자 없고, 타입 안 맞아서 터졌네?

    [ BoardCountDTO 한테 ]

    notion image
    생성자를 주고, 카운트 타입 친거는 Long 타입으로 바꿔야함 (다른것들도 래핑시켜주자)

    [ 다시 테스트하면? ]

    notion image
    notion image
    notion image
    notion image
    notion image
    댓글 1,2,3,4 다 나왔죠? 좋죠? 이거 쓰세요 ^^
     

     
     
    Share article

    codingb

    RSS·Powered by Inblog