스프링 부트, 입문!

스프링 부트, 입문!

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

15 데이터 수정(update)하기

# 데이터 수정하기 ## 미션 데이터를 수정하고, 이를 확인하시오. ![홍팍-스프링-부트-입문-데이터-수정-미션](http://drive.google.com/uc?export=view&id=1e-WTwyIMcj5j3cjbqunXMHnVMdt8zR8j) ## 03:33 더미 데이터 작성 - data.sql, insert into #### ../resources/data.sql ``` -- 15강: article 더미 데이터 INSERT INTO article(id, title, content) VALUES(1, '가가가가', '1111'); INSERT INTO article(id, title, content) VALUES(2, '나나나나', '2222'); INSERT INTO article(id, title, content) VALUES(3, '다다다다', '3333'); ``` ## ⚠️  failed to execute sql script statement 에러 발생 시 #### ../resources/application.properties ``` # 09강: h2 DB, 웹 콘솔 설정 spring.h2.console.enabled=true # 15강: data.sql 적용을 위한 설정(스프링부트 2.5 이상 필수) spring.jpa.defer-datasource-initialization=true ``` ## ⚠️  한글 깨짐 발생 시, “인텔리제이 한글 깨짐"으로 구글링! #### 메뉴바 > Help > VM 옵션 수정 다음 설정을 끝부분에 추가한다. ``` -Dfile.encoding=UTF-8 ``` #### 메뉴바 > File > Settings(or Preferences) > ... > File Encodings 설정 Global Encoding, Project Encoding, Properties Files 모두를 `UTF-8`로 바꾼다. <img src="http://drive.google.com/uc?export=view&id=1dcTx9u2ugFJ3zSpwBTZyaGGXN4LeRrlP" alt="홍팍-스프링-부트-인텔리제이-한글깨짐-인코딩"> ## 05:16 수정 페이지 변경 - form, action, method, post, patch #### ../articles/edit.mustache ``` {{>layouts/header}} {{#article}} <form class="container" action="/articles/update" method="post"> <input name="id" type="hidden" value="{{id}}" /> <div class="mb-3"> <label class="form-label">제목</label> <input type="text" class="form-control" name="title" value="{{title}}"> </div> <div class="mb-3"> <label class="form-label">내용</label> <textarea class="form-control" rows="3" name="content">{{content}}</textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> <a href="/articles/{{id}}">Back</a> </form> {{/article}} {{>layouts/footer}} ``` ## 07:28 수정 폼 받기 - Controller, PatchMapping, PostMapping, DTO #### ../controller/ArticleController ``` ... @Controller @Slf4j public class ArticleController { ... @PostMapping("/articles/update") public String update(ArticleForm form) { log.info(form.toString()); return ""; } } ``` ## 08:36 DTO 변경 - id 필드 추가 및 엔티티 변환 메소드 변경 #### ../dto/ArticleForm ``` package com.example.firstproject.dto; import com.example.firstproject.entity.Article; import lombok.AllArgsConstructor; import lombok.ToString; @AllArgsConstructor @ToString public class ArticleForm { private Long id; private String title; private String content; public Article toEntity() { return new Article(id, title, content); } } ``` ## 09:59 수정 폼 처리하기 #### ../controller/ArticleController ``` ... @Controller @Slf4j public class ArticleController { ... @PostMapping("/articles/update") public String update(ArticleForm form) { log.info(form.toString()); // 1: DTO를 엔티티로 변환 Article articleEntity = form.toEntity(); log.info(articleEntity.toString()); // 2: 엔티티를 DB로 저장 // 2-1: DB에서 기존 데이터를 가져옴 Article target = articleRepository.findById(articleEntity.getId()) .orElse(null); // 2-2: 기존 데이터가 있다면, 값을 갱신 if (target != null) { articleRepository.save(articleEntity); } // 3: 수정 결과 페이지로 리다이렉트 return "redirect:/articles/" + articleEntity.getId(); } } ``` ## 🔥 구글링 훈련하기 - jpa data.sql 사용법 - jpa defer-datasource-initialization - 인텔리제이 한글 깨짐