Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

데이터 목록 조회하기 본문

Spring/게시판 만들기

데이터 목록 조회하기

빌드이너프 2023. 9. 12. 16:46

단일 데이터가 아닌 여러 데이터 즉, 데이터 목록 조회

단일 데이터 조회: repository가 entity를 반환

데이터 목록 조회: entity 묶음인 리스트 반환

 

URL 요청받기

데이터 목록 조회는 localhost:8080/articles라는 URL 요청이 왔을 때 처리

ArticleController에서 show() 메서드 아래에 index() 메서드 추가

index() 메서드에 @GetMapping("/articles") 선언

@GetMapping("/articles/{id}")
public String show(@PathVariable Long id, Model model) {
    log.info("id = " + id);
    Article articleEntity = articleRepository.findById(id).orElse(null);

    model.addAttribute("article", articleEntity);
    return "articles/show";
}

@GetMapping("/articles")
public String index() {
    return "";
}

 

데이터 조회 후 출력

1. DB에서 모든 Article 데이터 가져오기

DB에서 데이터를 가져오려면 repository 필요

=> articleRepository에서 findAll()이라는 메서드 선택(articleRepository.findAll())

findAll(): 해당 repository에 있는 모든 데이터를 가져오는 메서드

데이터의 묶음을 받아오기 때문에 List<Article>, 이름은 articleEntityList

 

findAll() 메서드가 반환하는 타입은 Iterable인데 List라서 에러 메시지 발생

=> Iterable이 아닌 ArrayList 반환하도록 수정

com.example.firstproject>repository>ArticleRepository을 보면

ArticleRepository가 CurdRepository를 상속받고 있다

 

CrudRepository의 메서드를 오버라이딩해준다

Generate -> Override Methods에서 findAll():Iterable<T> 선택

Iterable 타입을 ArrayList로 바꾼다

package com.example.firstproject.repository;

import com.example.firstproject.entity.Article;
import org.springframework.data.repository.CrudRepository;

import java.util.ArrayList;

public interface ArticleRepository extends CrudRepository<Article, Long> {
    @Override
    ArrayList<Article> findAll(); // Iterable -> ArrayList 수정
}

 

정확하게 하려면 articleEntityList의 타입을 List<Article>이 아닌 ArrayList<Article>로 해야한다

하지만 여기에선 ArrayList의 상위 타입인 List로 업캐스팅

 

 

 

2. 가져온 Article 묶음을 모델에 등록하기

index() 메서드의 매개변수로 model 객체를 받아온다

model.addAttribute() 메서드로 전달할 데이터 묶음인 articleEntityList를 "articleList"라는 이름으로 등록한다

@GetMapping("/articles")
public String index(Model model) {
    List<Article> articleEntityList = articleRepository.findAll();
    model.addAttribute("articleList", articleEntityList);
    return "";
}

 

3. 사용자에게 보여 줄 View 페이지 설정

articles 디렉터리 안에 index.mustache 파일이 view 페이지로 설정될 수 있도록 return 문 작성

@GetMapping("/articles")
public String index(Model model) {
    List<Article> articleEntityList = articleRepository.findAll();
    model.addAttribute("articleList", articleEntityList);
    return "articles/index";
}

 

index.mustache 파일 작성

resource>templates>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>
        <tr>
            <th scope="row">{{id}}</th>
            <td colspan="1">{{title}}</td>
            <td>{{content}}</td>
        </tr>
    </tbody>
</table>

{{>layouts/footer}}

 

Controller에서 articleList라는 이름으로 articleEntity를 등록했다

view 페이지에서 모델에 등록한 articleList를 받아오면 된다({{#articleList}}, {{/articleList}})

{{>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 scope="row">{{id}}</th>
            <td colspan="1">{{title}}</td>
            <td>{{content}}</td>
        </tr>
    {{/articleList}}
    </tbody>
</table>

{{>layouts/footer}}

 

서버 재시작 후 데이터 입력

localhost:8080/articles/new

제목(qwer), 내용(1234)

제목(asdf), 내용(5678)

 

localhost:8080/articles에 접속하면 데이터가 잘 출력됨

 

 

'Spring > 게시판 만들기' 카테고리의 다른 글

수정 페이지 만들기  (0) 2023.09.13
link와 redirect를 이용해 페이지 연결  (0) 2023.09.12
게시글 읽기 Read  (0) 2023.09.12
Lombok  (0) 2023.09.12
데이터 조회  (0) 2023.09.11