저번에는 댓글 기능을 추가해서, 해당 Board_table의 Id값을 참조해
댓글 작성하는 기능을 구현했다면,
지금 시간에는 댓글 조회 기능을 추가해볼 예정이다.
조회를 할때 필요한건 해당 내용들을 출력(조회) 할 수 있는 기능이 필요한데.
먼저 DTO를 새로 만들고 해당 DTO를 사용해 목록출력 기능을 구현해보자
CommentDetailDTO
@Data public class CommentDetailDTO { private Long commentId; private Long boardId; private String commentWriter; private String commentContents; private LocalDateTime createTime;
이렇게 먼저 목록 및 조회에 출력할 값들을 필드값으로 준다.
Controller
@PostMapping("/save") public @ResponseBody List<CommentDetailDTO> save(@ModelAttribute CommentSaveDTO commentSaveDTO){ cs.save(commentSaveDTO); List<CommentDetailDTO> commentList = cs.findAll(commentSaveDTO.getBoardId()); return commentList; }
save 메서드에 한 줄만 추가하면 된다.
commentSaveDTO 값을 cs.findAll안에 담아주고 해당 담아준 값들을
목록으로 출력해야 하기 때문에 List를 사용해준다.
즉List<CommentDetailDTO> commentList
에 cs.findAll 값을 담아주면 끝!
그럼 Service와 ServiceImpl에 findAll을 만들어야하니까...
Service
List<CommentDetailDTO> findAll(Long boardId);
ServiceImpl
@Override public List<CommentDetailDTO> findAll(Long boardId) { BoardEntity boardEntity = br.findById(boardId).get(); List<CommentEntity> commentEntityList = boardEntity.getCommentEntityList(); List<CommentDetailDTO> commentList = new ArrayList<>(); for(CommentEntity c: commentEntityList) { CommentDetailDTO commentDetailDTO = CommentDetailDTO.toCommentDetailDTO(c); commentList.add(commentDetailDTO); } return commentList; }
코드를 읽어보자....
BoardEntity 를 사용하는 boardEntity라는 변수를 선언하고
br.findById(boardId).get();
해당 boardId 값을 담아준다.(참조)
목록 출력을 위해 리스트로 commentEntityList를 선언하고
boardEntity에 commentEntityList 즉 댓글 정보를 담아준다.
똑같이 몰록 출력을 위해 리스트로 CommentDetailList를
commentList로 선언 해 주고(값 담기 용도)
forEach 문을 사용하여 댓글 정보들이 commentList에 담기게
하면 끝!!
return은 당연히 commentList를 넘겨준다.
여기서 toCommentDetailDTO(c) 를 commentDetailDTO 에 담아주는데
toCommentDetailDTO를 사용하기 위해서는 당연히
CommentDetailDTO에 매서드를 만들어줘야한다.
CommentDetailDTO(toCommentDetailDTO)
public static CommentDetailDTO toCommentDetailDTO(CommentEntity commentEntity) { CommentDetailDTO commentDetailDTO = new CommentDetailDTO(); commentDetailDTO.setCommentId(commentEntity.getId()); commentDetailDTO.setCommentWriter(commentEntity.getCommentWriter()); commentDetailDTO.setCommentContents(commentEntity.getCommentContents()); commentDetailDTO.setCreateTime(commentEntity.getCreateTime()); commentDetailDTO.setBoardId(commentEntity.getBoardEntity().getId()); return commentDetailDTO; }