스프링 부트, 입문!

스프링 부트, 입문!

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

11 데이터 조회(read)하기 with JPA

# 데이터 조회하기 with JPA ## 미션 DB속 데이터를 조회하여, 웹 페이지로 확인하시오. ![홍팍-스프링-부트-입문-데이터-조회-미션](http://drive.google.com/uc?export=view&id=1dv5vKzpuW2jlkApyEAYOeFUgo3x-JZQC) ## 02:24 URL 요청받기 - PathVariable #### ../controller/ArticleController ``` ... @Controller @Slf4j public class ArticleController { ... @GetMapping("/articles/{id}") // 해당 URL요청을 처리 선언 public String show(@PathVariable Long id) { // URL에서 id를 변수로 가져옴 log.info("id = " + id); return ""; } } ``` ## 04:59 컨트롤러 - 처리 흐름 #### ../controller/ArticleController ``` ... @Controller @Slf4j public class ArticleController { ... @GetMapping("/articles/{id}") // 해당 URL요청을 처리 선언 public String show(@PathVariable Long id) { // URL에서 id를 변수로 가져옴 log.info("id = " + id); // 1: id로 데이터를 가져옴! // 2: 가져온 데이터를 모델에 등록! // 3: 보여줄 페이지를 설정! return ""; } } ``` ## 05:36 리파지터리 - id 조회, findById() #### ../controller/ArticleController ``` ... public class ArticleController { ... @GetMapping("/articles/{id}") // 해당 URL요청을 처리 선언 public String show(@PathVariable Long id, Model model) { // URL에서 id를 변수로 가져옴 log.info("id = " + id); // 1: id로 데이터를 가져옴! Article articleEntity = articleRepository.findById(id).orElse(null); // 2: 가져온 데이터를 모델에 등록! model.addAttribute("article", articleEntity); // 3: 보여줄 페이지를 설정! return "articles/show"; } } ``` ## 09:00 뷰 - mustache 템플릿 작성 #### ../articles/show.mustache ``` {{>layouts/header}} <table class="table"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Title</th> <th scope="col">Content</th> </tr> </thead> <tbody> {{#article}} <tr> <th>{{id}}</th> <td>{{title}}</td> <td>{{content}}</td> </tr> {{/article}} </tbody> </table> {{>layouts/footer}} ``` ## 13:17 디버깅 - 디폴트 생성자 추가, NoArgsConstructor #### ../entity/Article ``` package com.example.firstproject.entity; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.ToString; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity @AllArgsConstructor @NoArgsConstructor // 디폴트 생성자 추가 @ToString public class Article { @Id @GeneratedValue private Long id; @Column private String title; @Column private String content; } ``` ## 🔥 구글링 훈련하기 - @PathVariable - JPA CrudRepository findById 사용법 - @NoArgsConstructor - Java Optional 사용법