[Spring Boot] #12 데이터 목록 조회

gogori6565·2024년 6월 21일
0

스프링 부트 공부

목록 보기
10/20

👉 Mission. DB속 모든 Article을 목록으로 조회하시오


💻 데이터 목록 조회 - 실습

흐름이 이전 시간의 #11 데이터 조회 와 비슷하므로 일부 생략하고 가겠음

1. 데이터 목록 조회 페이지 설정 (요청 url 받기)

파일명 : controller/ArticleController.java

@GetMapping("/articles")
    public String index(){

        //1. 모든 Article을 가져온다!

        //2. 가져온 Article 묶음을 view로 전달

        //3. 뷰 페이지를 설정!

        return "";
    }

2. 모든 Article 가져오기

//1. 모든 Article을 가져온다!
List<Article> articleEntityList = articleRepository.findAll(); //타입 불일치 에러 발생!

🛑 에러 해결법

  1. 캐스팅
    List<Article> articleEntityList = (List<Article>)articleRepository.findAll();

  2. 받을 변수를 리턴 타입으로 맞춰주기
    Iterable<Article> articleEntityList = articleRepository.findAll();

  3. 메소드 오버라이딩
    ArticleRepository 에서 상속 받은 CrudRepository의 메소드를 오버라이딩 해주기
    우클릭>Gernerate>Override Methods : findAll() 메소드 오버라이드 해주기

@Override
Iterable<Article> findAll();

-> 변경

@Override
ArrayList<Article> findAll();

즉, article.Repository.findAll()의 반환타입을 Iterable 이 아닌 ArrayList로 변경해줌!

ArrayList는 상위타입인 List로 업캐스팅 할 수 있다.
따라서 List<Article> articleEntityList = articleRepository.findAll(); 오류 해결!

3. 가져온 Article 묶음을 데이터 Model에 등록

//2. 가져온 Article 묶음을 view로 전달
model.addAttribute("articleList", articleEntityList);

4. View 페이지 만들기

//3. 뷰 페이지를 설정!
return "articles/index.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>
    {{#articleList}}
        <tr>
            <th>{{id}}</th>
            <td>{{title}}</td>
            <td>{{content}}</td>
        </tr>
    {{/articleList}}
    </tbody>
</table>

{{>layouts/footer}}
  • {{#articleList}}가 여러 데이터의 묶음일 경우, 머스테치에서 {{#articleList}}~{{/articleList}} 사이 코드가 반복되어 출력된다.
    (따라서 모든 데이터를 view에 표시할 수 있음)

<결과 화면>


📚정리

#11 데이터 조회하기 의 내용과 흐름이 같음.

특별히 다른 점
: 반환하는 결과가 Entity의 묶음인 ‘List’라는 점, mustache에서 {{}}으로 그 묶음 데이터를 반복할 수 있다는 점!


강의 출처 : https://www.youtube.com/watch?v=_vDACE13Ubc&list=PLyebPLlVYXCiYdYaWRKgCqvnCFrLEANXt&index=1 [스프링 부트 입문 - 홍팍]

profile
p(´∇`)q

0개의 댓글