SpringBoot(홍팍) - 데이터 조회하기 with JPA

정원·2023년 3월 14일
0

SpringBoot

목록 보기
17/34

2023.03.14 데이터 조회하기 with JPA

URL 요청 받기

ArticleController에 메소드 추가.
Mapping URL에 변하는값을 { }에 넣고
파라미터로 URL에서 가져오는 값이라는 뜻의 @PathVariable을 사용한다.

@GetMapping("/articles/{id}")
    public String show(@PathVariable Long id) {
        log.info("id:" + id);
        return "";
    }

1: id로 데이터를 가져옴

repository에 findById사용

@GetMapping("/articles/{id}")
    public String show(@PathVariable Long id) {
        log.info("id:" + id);
        
        // 1: id로 데이터를 가져옴
        Article articleEntity = articleRepository.findById(id).orElse(null);
        // articleRepository 리턴 타입이 Optional이기 때문에 .orElse(null) 사용
        // 해당 id 값 없으면 null 반환
        
        // 2: 가져온 데이터를 모델에 등록
        
        // 3: 보여줄 페이지를 설정
        return "";
    }

2: 가져온 데이터를 모델에 등록

파라미터에 Model model 추가.
addAttribute에 articleEntity주기.

@GetMapping("/articles/{id}")
    public String show(@PathVariable Long id, Model model) {
        log.info("id:" + id);
        
        // 1: id로 데이터를 가져옴
        Article articleEntity = articleRepository.findById(id).orElse(null);
        // articleRepository 리턴 타입이 Optional이기 때문에 .orElse(null) 사용
        // 해당 id 값 없으면 null 반환
        
        // 2: 가져온 데이터를 모델에 등록
        model.addAttribute("article", articleEntity);
        // 3: 보여줄 페이지를 설정
        return "articles/show";
    }

3: 보여줄 페이지를 설정

show.mustache 생성

{{>layouts/header}}

<table class="table table-striped">
    <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}}
<!--  article의 닫는 태그 작성해주기  -->
    </tbody>
</table>

{{>layouts/footer}}

에러

보여줄 페이지도 생성했으니 요청을 보내보자 .
http://localhost:8080/articles/1 요청을 보내면 아래와 같은 에러가 발생한다.
Entity에 기본 생성자가 없다.

Article.java에 기본 생성자 lombok으로 추가.
@NoArgsConstructor

@AllArgsConstructor
@NoArgsConstructor // 디폴트 생성자 추가!
@ToString
@Entity // 1.DB가 해당 객체를 인식 가능하게 됨.
public class Article {
	...
}

기본생성자 추가 후 데이터 넣고 조회하면 성공적으로 확인가능!! ✨ ![](https://velog.velcdn.com/images/jwons44/post/17c26064-1c6e-4d54-b529-e0d51073bb51/image.png)

0개의 댓글