게시물 상세 조회를 할 경우 댓글도 보이게 하는 메서드를 작성했다. 그렇지만 처음에 매우 생각이 안나서 코드 망치고 했으나 생각보다 너무 간단하였다....ㅠ
PostResponseDto
@Getter
public class PostResponseDto {
private Long id;
private String title;
private String username;
private String contents;
private LocalDateTime createdAt;
private LocalDateTime modifiedAt;
private List<CommentResponseDto> comments;
public PostResponseDto(Post post) {
this.id = post.getId();
this.title = post.getTitle();
this.username = post.getUser().getUsername();
this.contents = post.getContents();
this.createdAt = post.getCreatedAt();
this.modifiedAt = post.getModifiedAt();
this.comments = post.getCommentList().stream()
.map(CommentResponseDto::new)
.toList();
}
}
- 게시물 응답 Dto 에서 comment의 리스트를 가지고 온다.
- 생성자에는 Post객체를 매개변수로 받아서 PostResponseDto 객체를 생성함
- Post 객체에 달린 댓글들을 CommentResponseDto 객체로 매핑하고 리스트로 저장
- stream() : 리스트를 스트림으로 변환하여 요소에 대해 연속적인 작업 수행 (for문 사용한다고 생각)
- map(CommentResponseDto::new) : 각 댓글들을 CommentResponseDto 객체로 변환
- toList() : 스트림의 요소를 리스트로 변경
(아직 stream메서드에 대해서 헷갈려서 자세하게 적어보았다..)
PostController
* 게시글을 가져올때 댓글이 보이게 할 때 PostResponseDto빼고는 건드릴 부분이 없다.
// 선택한 게시물 조회
@GetMapping("/post/inquiry/{id}")
public PostResponseDto getPost(@PathVariable Long id) {
return postService.getPost(id);
}
PostService
public PostResponseDto getPost(Long id) {
Post post = findPost(id);
return new PostResponseDto(post);
}
반응형
'study > study_spring' 카테고리의 다른 글
[S.A] TDL 프로젝트 (0) | 2023.07.17 |
---|---|
[TIL] 좋아요 기능 구현 (Java) (0) | 2023.07.12 |
[TIL] 회원가입 구현 (0) | 2023.06.26 |
[TIL] @Builder (0) | 2023.06.22 |
[TIL] IntelliJ IDEA에서 Gradle을 인식 못했을 때 (0) | 2023.06.21 |