48. 응답 DTO - DTO로 바로 받기v7

송민경's avatar
Mar 21, 2024
48. 응답 DTO - DTO로 바로 받기v7

1. 쿼리 작성하

select * from board_tb where id = 4; select count(id) from reply_tb where board_id = 4; select id, title, content, 4 reply_count from board_tb; select id, title, content, user_id, 4 reply_count from board_tb bt; 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
 
package shop.mtcoding.blog.board; import lombok.AllArgsConstructor; import lombok.Data; import shop.mtcoding.blog.reply.Reply; import shop.mtcoding.blog.user.User; import java.util.ArrayList; import java.util.List; public class BoardResponse { @AllArgsConstructor @Data public static class CountDTO { private Integer id; private String title; private String content; private Integer userId; private Long replyCount; } }
 
package shop.mtcoding.blog.board; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Optional; public interface BoardJPARepository extends JpaRepository<Board, Integer> { @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(); @Query("select b from Board b join fetch b.user u where b.id = :id") Optional<Board> findByIdJoinUser(@Param("id") int id); }
package shop.mtcoding.blog.Board; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.data.domain.Sort; import shop.mtcoding.blog.board.Board; import shop.mtcoding.blog.board.BoardJPARepository; import shop.mtcoding.blog.board.BoardResponse; import shop.mtcoding.blog.user.User; import java.util.List; import java.util.Optional; @DataJpaTest public class BoardJPARepositoryTest { @Autowired private BoardJPARepository boardJPARepository; @Test public void findAllWithReplyCount_test(){ // given // when List<BoardResponse.CountDTO> boardCountDTOList = boardJPARepository.findAllWithReplyCount(); System.out.println(boardCountDTOList); // then } }
notion image
[BoardCountDTO(id=1, title=제목1, content=내용1, userId=1, replyCount=0), BoardCountDTO(id=2, title=제목2, content=내용2, userId=1, replyCount=0), BoardCountDTO(id=3, title=제목3, content=내용3, userId=2, replyCount=1), BoardCountDTO(id=4, title=제목4, content=내용4, userId=3, replyCount=3)]
Share article
RSSPowered by inblog