![](https://velog.velcdn.com/images%2Fdrv98%2Fpost%2F37cc6dc3-d317-4c11-bb9e-2ff0c7164a48%2Fimage.png)
1. 서비스
// id 로 댓글 업데이트
CommentDto updateCommentById(Long postId, CommentDto commentRequest);
2. 서비스 구현
@Override
public CommentDto updateCommentById(Long postId, Long commentId, CommentDto commentDto) {
//ID 로 포스트 찾기 못찾을 경우 예외처리
Post post = postRepository.findById(postId).orElseThrow(() -> new ResourceNotFoundException("Post", "id", postId));
//ID 로 댓글 찾기 못찾을 경우 예외
Comment comment = commentRepository.findById(commentId).orElseThrow(() -> new ResourceNotFoundException("Comment", "id", commentId));
if(!comment.getPost().getId().equals(post.getId())) {
throw new BlogAPIException(HttpStatus.BAD_REQUEST, "해당 포스트의 댓글이 아닙니다.");
}
comment.setName(commentDto.getName());
comment.setEmail(commentDto.getEmail());
comment.setBody(commentDto.getBody());
Comment updatedComment = commentRepository.save(comment);
return mapToDTO(updatedComment);
}
컨트롤러
@PutMapping("/posts/{postId}/comments/{commentId}")
public ResponseEntity<CommentDto> getCommentsByPostID(
@PathVariable Long postId, @PathVariable Long commentId,
@RequestBody CommentDto commentDto
){
return new ResponseEntity<>(commentService.updateCommentById(postId, commentId, commentDto), HttpStatus.OK) ;
}
테스트
![](https://velog.velcdn.com/images%2Fdrv98%2Fpost%2F6f820849-e699-4074-9809-34d28affe5a0%2Fimage.png)
![](https://velog.velcdn.com/images%2Fdrv98%2Fpost%2Fed69d86b-d579-4b7c-809c-2beaf2146e1c%2Fimage.png)