2023.03.16 데이터 목록 조회
http://localhost:8080/articles
ArticleController.java 에 메소드 추가.
1: 모든 Article 가져오기
2: 가져온 Article 묶음을 뷰로 전달
3: 뷰 페이지를 설정
@GetMapping("/articles")
public String index() {
// 1: 모든 Article 가져오기
List<Article> articleEntityList = articleRepository.findAll();
// 2: 가져온 Article 묶음을 뷰로 전달
// 3: 뷰 페이지를 설정
return "";
}
findAll() 은 리턴 타입이 Iterable 이기 떄문에 에러가 발생한다.
해결 방법 1. 캐스팅하기
// 1: 모든 Article 가져오기
List<Article> articleEntityList = (List<Article>)articleRepository.findAll();
해결 방법 2. 리턴타입으로 받기
// 1: 모든 Article 가져오기
Iterable<Article> articleEntityList = articleRepository.findAll();
해결 방법 3. 메소드 오버라이딩
우클릭 - Generate - Overried Methods.. 선택
ArticleRepository.java에 Override를 통해서 리턴 타입을 변경한다.
findAll() 오버라이딩 후
리턴타입을 Iterable -> ArrayList로 변경.
public interface ArticleRepository extends CrudRepository<Article, Long> {
@Override
ArrayList<Article> findAll();
}
ArticleController에서 ArrayList로 받을수도 있지만 상위 타입인 List로 받자.
@GetMapping("/articles")
public String index() {
// 1: 모든 Article 가져오기
List<Article> articleEntityList = articleRepository.findAll();
// 2: 가져온 Article 묶음을 뷰로 전달
// 3: 뷰 페이지를 설정
return "";
}
@GetMapping("/articles")
public String index(Model model) {
// 1: 모든 Article 가져오기
List<Article> articleEntityList = articleRepository.findAll();
// 2: 가져온 Article 묶음을 뷰로 전달
model.addAttribute("articleList", articleEntityList);
// 3: 뷰 페이지를 설정
return "articles/index";
}
index.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>
{{#articleList}}
<tr>
<th>{{id}}</th>
<td>{{title}}</td>
<td>{{content}}</td>
</tr>
{{/articleList}}
</tbody>
</table>
{{>layouts/footer}}
mustache는 여러데이터의 묶음인 경우 안쪽내용이 반복되기 때문에
for문이 필요없이 자동으로 반복출력된다... 👍👍
List만 뿌려줬는데도 알아서 목록이 다 출력된다.