![](https://velog.velcdn.com/images%2Fdrv98%2Fpost%2F0ec28e95-2942-47e1-8ca6-617c582289e5%2Fimage.png)
1. 서비스
// id 로 댓글 삭제
void deleteCommentById(Long postId, Long commentId);
2. 서비스 구현
@Override
public void deleteCommentById(Long postId, Long commentId) {
//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, "해당 포스트의 댓글이 아닙니다.");
}
commentRepository.delete(comment);
}
컨트롤러
@DeleteMapping("/posts/{postId}/comments/{commentId}")
public ResponseEntity<String> deleteCommentById(@PathVariable long postId, @PathVariable long commentId){
commentService.deleteCommentById(postId, commentId);
return new ResponseEntity<>("성공적으로 삭제 완료.", HttpStatus.OK) ;
}
테스트
![](https://velog.velcdn.com/images%2Fdrv98%2Fpost%2F4e924479-9a61-4dff-92e0-19f317e59397%2Fimage.png)
![](https://velog.velcdn.com/images%2Fdrv98%2Fpost%2F26ec6722-92e7-4906-bd67-85e583e6ea29%2Fimage.png)