~15.6 댓글 삭제하기 (종이책 p.446~474)
ResponseEntity<CommentDto>로 작성한다.@PostMapping(”/api/articles/{articleId}/comments”)
public ResponseEntity<CommentDto> create(@PathVariable Long articleId, @RequestBody CommentDto dto) {
CommentDto createdDto = commentService.create(articleId, dto);
return ResponseEntity.status(HttpStatus.Ok).body(createdDto);
}
컨트롤러에 빨간색으로 표시된 create() 메서드 위에 마우스를 올리고 Create method ‘create’ in ‘CommentService’를 클릭한다.
@Transactional
public CommentDto create(Long articleId, CommentDto dto) {
Article article = articleRepository.findById(articleId).orElseThrow(() → new IllegalArgumentException(”댓글 생성 실패! “ + “대상 게시글이 없습니다.”));
Comment comment = Comment.createComment(dto, article);
Comment created = commentRepository.save(comment);
return CommentDto.createCommentDto(created);
}
public static Comment createComment(CommentDto dto, Article article) {
if(dto.getId() != null)
throw new IllegalArgumentException(”댓글 생성 실패! 댓글의 id가 없어야 합니다.”);
if(dto.getArticleId() != article.getId())
throw new IllegalArgumentException(”댓글 생성 실패! 게시글의 id가 잘못됐습니다.”);
return new Comment(dto.getId(), article, dto.getNickname(), dto.getBody());
}
※ JSON 데이터의 키(key) 이름과 이를 받아 저장하는 DTO에 선언된 필드의 변수명이 다를 경우 DTO 필드 위에 @JsonProperty(”키_이름”)을 작성해 줘야 한다. 이렇게 하면 해당 키와 변수가 자동으로 매핑된다.
@PatchMapping(”/api/comments/{id}”)
public ResponseEntity<CommentDto> update(@PathVariable Long id, @RequestBody CommentDto dto) {
CommentDto updatedDto = commentService.update(id, dto);
return ResponseEntity.status(HttpStatus.OK).body(updatedDto);
}
@Transactional
public CommentDto update(Long id, CommentDto dto) {
Comment target = commentRepository.findById(id).orElseThrow(() → new IllegalArgumentException(”댓글 수정 실패! ” + “대상 댓글이 없습니다.”));
target.patch(dto);
Comment updated = commentRepository.save(target);
return CommentDto.createCommentDto(updated);
}
public void patch(CommentDto dto) {
if(this.id != dto.getId())
throw new IllegalArgumentException(”댓글 수정 실패! 잘못된 id가 입력됐습니다.”);
if(dto.getNickname() != null)
this.nickname = dto.getNickname();
if(dto.getBody() != null)
this.body = dto.getBody();
}
ResponseEntity<CommentDto>로 작성한다.@DeleteMapping(”/api/comments/{id}”)
public ResponseEntity<CommentDto> delete(@PathVariable Long id) {
CommentDto deletedDto = commentService.delete(id);
return ResponseEntity.status(HttpStatus.OK).body(deletedDto);
}
@Transactional
public CommentDto delete(Long id) {
Comment target = commentRepository.findById(id).orElseThrow(() → new IllegalArgumentException(”댓글 삭제 실패! “ + “대상이 없습니다.”));
commentRepository.delete(target);
return CommentDto.createCommentDto(target);
}