스프링 부트, 입문!

스프링 부트, 입문!

쉽고 빠르게 배우는, 스프링 부트 첫걸음!

16 데이터 삭제(delete)하기

# 데이터 삭제하기 ## 미션 데이터를 삭제하고 그 결과를 확인하시오. ![홍팍-스프링-부트-입문-데이터-삭제-미션](http://drive.google.com/uc?export=view&id=1e0VCCSMVUftkYVJXGD4-GBuB6x_KyNbN) ## 02:18 삭제 버튼 추가 - a 태그와 HTTP 메소드 #### ../articles/show.mustache ``` {{>layouts/header}} <table class="table"> ... </table> <a href="/articles/{{article.id}}/edit" class="btn btn-primary">Edit</a> <!-- 삭제 링크 추가 --> <a href="/articles/{{article.id}}/delete" class="btn btn-danger">Delete</a> <a href="/articles">Go to Article List</a> {{>layouts/footer}} ``` ## 05:19 삭제 요청 받기 - Controller, GetMapping, DeleteMapping #### ../controller/ArticleController ``` ... @Controller @Slf4j public class ArticleController { ... @GetMapping("/articles/{id}/delete") public String delete(@PathVariable Long id) { log.info("삭제 요청이 들어왔습니다!!"); // 1: 삭제 대상을 가져옴 Article target = articleRepository.findById(id).orElse(null); log.info(target.toString()); // 2: 대상을 삭제 if (target != null) { articleRepository.delete(target); } // 3: 결과 페이지로 리다이렉트 return "redirect:/articles"; } } ``` ## 13:26 삭제 완료 메시지 - RedirectAttributes, addFlashAttribute #### ../controller/ArticleController ``` ... @Controller @Slf4j public class ArticleController { ... @GetMapping("/articles/{id}/delete") public String delete(@PathVariable Long id, RedirectAttributes rttr) { log.info("삭제 요청이 들어왔습니다!!"); // 1: 삭제 대상을 가져옴 Article target = articleRepository.findById(id).orElse(null); log.info(target.toString()); // 2: 대상을 삭제 if (target != null) { articleRepository.delete(target); rttr.addFlashAttribute("msg", "삭제가 완료되었습니다."); } // 3: 결과 페이지로 리다이렉트 return "redirect:/articles"; } } ``` #### ../layouts/header.mustache ``` <!doctype html> <html lang="en"> <head> ... <body> <!-- navigation --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> ... </nav> <!-- alert msg --> {{#msg}} <div class="alert alert-primary alert-dismissible"> {{msg}} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {{/msg}} ``` ## 🔥 구글링 훈련하기 - JPA Repository delete - Spring RedirectAttributes addFlashAttribute - Bootstrap Alert