~15.3 댓글 조회하기(종이책 p.427~445)
이 장에서는 댓글 REST 컨트롤러, 서비스, DTO를 만들어 댓글 CRUD를 위한 REST API를 완성한다.

댓글 CRUD를 하려면 REST API 주소가 필요하다. 여기서는 다음과 같이 설정한다.
댓글 REST API를 구현하기 위해 api 패키지에 REST 컨트롤러를 만든다.
@RestController
public class CommentApiController {
@Autowired
private CommentService commentService;
}
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
@Autowired
private ArticleRepository articleRepository;
}
이제 컨트롤러가 처리할 기능을 하나씩 구현해 본다. (댓글 조회, 생성, 수정, 삭제)
댓글을 조회할 때 REST API 주소는 /articles/articleId/comments 이다. 이 주소로 댓글 조회 요청을 보내고 응답을 받도록 한다.
ResponseEntity<List<CommentDto>>로 정의한다. DB에서 조회한 댓글 엔티티 목록은 List<Comment>이지만, 엔티티를 DTO로 변환하면 List<CommentDto>가 되기 때문이다. 응답 코드도 같이 보내기 위해 ResponseEntity 클래스를 활용한다.List<CommentDto> 타입의 dtos라는 변수에 저장한다. @GetMapping(”/api/articles/{articleId}/comments”)
public ResponseEntity<List<CommentDto>> comments(@PathVariable Long articleId) {
List<CommentDto> dtos = commentService.comments(articleId);
return ResponseEntity.status(HttpStatus.OK).body(dtos);
}
@AllArgsConstructor
@NoArgsConstructor
@Getter
@ToString
public class CommentDto {
private Long id;
private Long articleId;
private String nickname;
private String body;
}
public List<CommentDto> comments(Long articleId) {
List<Comment> comments = commentRepository.findByArticleId(articleId);
List<CommentDto> dtos = new ArrayList<CommentDto>();
for (int i = 0; i < comments.size(); i++) {
Comment c = comments.get(i);
CommentDto dto = CommentDto.createCommentDto(c);
dtos.add(dto);
}
return dtos;
}
public static CommentDto createCommentDto(Comment comment) {
return new CommentDto(
comment.getId(), // 댓글 엔티티의 id
comment.getArticle().getId(), // 댓글 엔티티가 속한 부모 게시글의 id
comment.getNickname(), // 댓글 엔티티의 nickname
comment.getBody() // 댓글 엔티티의 body
);
}
서버를 실행한 후 Talend API Tester 에서 GET 메서드를 http://localhost:8080/api/articles/4/comments URL로 보내면 성공 응답이 오는 것을 확인할 수 있다.
방금 만들었던 서비스 코드의 for문을 스트림(stream) 문법으로 개선해본다.
public List<CommentDto> comments(Long articleId) {
return commentRepository.findByArticleId(articleId) // 댓글 엔티티 목록 조회
.stream() // 댓글 엔티티 목록을 스트림으로 변환
.map(comment → CommentDto.createCommentDto(comment)) // 엔티티를 DTO로 매핑
.collect(Collectors.toList()); // 스트림을 리스트로 변환
}