[스프링부트]4.3 삭제 기능 구현하기

Bummy·2022년 8월 22일
0

springboot

목록 보기
9/15

오늘은 지난 포스팅에 이어서 삭제 기능을 구현할 것이다.

게시글 삭제

  1. 수정 화면에 삭제 버튼을 추가해준다.

  1. 삭제를 진행할 JS 코드를 index.js에 추가해준다.
    index.js
 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));
        });
    }

  1. 삭제 API를 만들어준다.
    PostsService
 @Transactional
    public  void delete (Long id){
        Posts posts = postsRepository.findById(id).orElseThrow(()-> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));

        postsRepository.delete(posts); //JpaRepository에서 이미 delete를 지원하고 있어 이를 활용한다.
    }
  • postsRepository.delete(posts) : JpaRepository에서 이미 delete 메소드를 지원하고 있어 이를 활용한다.
    엔티티를 파라미터로 삭제할 수 있고, deleteById 메소드를 이용하면 id로 삭제할 수도 있다.

4.PostsApiController

 @DeleteMapping("/api/v1/posts/{id}")
   public Long delete(@PathVariable Long id){
       postsSerivce.delete(id);
       return id;
   }

삭제를 위한 Controller까지 추가해주면 된다.


테스트


삭제를 위해 게시글 수정 화면에서 "삭제" 버튼을 눌러준다.

이후 알럿창이 나오며

글이 삭제된 것을 확인할 수 있다.

0개의 댓글