오늘은 지난 포스팅에 이어서 삭제 기능을 구현할 것이다.
delete : function (){
var id = $('#id').val();
$.ajax({
type : 'DELETE',
url : '/api/v1/posts/'+id,
dataType : 'json',
contentType : 'application/json; charset=utf-8'
}).done(function (){
alert('글이 삭제되었습니다.');
window.location.href = '/';
}).fail(function (error){
alert(JSON.stringify(error));
});
}
@Transactional
public void delete (Long id){
Posts posts = postsRepository.findById(id).orElseThrow(()-> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
postsRepository.delete(posts); //JpaRepository에서 이미 delete를 지원하고 있어 이를 활용한다.
}
4.PostsApiController
@DeleteMapping("/api/v1/posts/{id}")
public Long delete(@PathVariable Long id){
postsSerivce.delete(id);
return id;
}
삭제를 위한 Controller까지 추가해주면 된다.
삭제를 위해 게시글 수정 화면에서 "삭제" 버튼을 눌러준다.
이후 알럿창이 나오며
글이 삭제된 것을 확인할 수 있다.