본문 바로가기

Study/SpringBoot

[스프링 부트 입문 12]데이터 목록조회

728x90
* 학습목표
- DB 속 모든 Article 목록으로 조회하시오.

1. 브라우저 요청 받기.
controller/ArticleController
@GetMapping("/articles") 이라는 URL로 받아온다.

2. 컨트롤러 처리 흐름
- 1. 모든 Article을 가져온다!
- 2. 가져온 Article 묶음을 뷰로 전달!
- 3. 뷰 페이지를 설정!

3. 타입 캐스팅
- 데이터 타입이 맞지않아 빨간줄 뜨는데 해결방법 3가지
- findAll() 메서드 : 해당 Repository에 있는 모든 데이터를 받아옴.

-- 1. 우리에게 익숙한 Array List 사용
- List<Article> articleEntityList = articleRepository.findAll();
-- 2. Iterable 타입으로 맞춰준다.
- Iterable<Article> articleEntityList = articleRepository.findAll();
-- 3. 캐스팅 해주는 방법.
- List<Article> articleEntityList = (List<Article>)articleRepository.findAll();

4. 메소드 오버라이딩
repository/ArticleRepository
@OverRide //오버라이드 해줌, 그래야 타입 불일치 오류를 해결할 수 있음.
ArrayList<Article> findAll();

5. 모델에 데이터 등록
public String index(Model model){ 모델을 통해서
model.addAttribute("articleList", articleEntityList);
                      변수이름             던져줄 데이터

6. 뷰 페이지 연결
return "articles/index"; // articles/index.mustache

7. 뷰 페이지 작성
articles/index.mustache 뷰페이지 생성
{{#articleList}}
   <tr>
       <th>{{id}}</th>
       <td>{{title}}</td>
       <td>{{content}}</td>
   </tr>
{{/articleList}}
mustache 리스트 출력

8. 동작확인
http://localhost:8080/articles
오오 잘 동작함 ~

8. + 머스테치 반복 출력
for문이랑 원리가 비슷함.
{{#articleList}}
   <tr>
       <th>{{id}}</th> 1번
       <td>{{title}}</td> 2번
       <td>{{content}}</td> 3번
   </tr>
{{/articleList}}
반복 ~~

https://github.com/Giltaehyeong/firstproject/commit/0e997f0a521b0571d454eaf6beef279b33f6adcc

 

[스프링 부트 입문 12]데이터 목록조회 · Giltaehyeong/firstproject@0e997f0

* 학습목표 - DB 속 모든 Article 목록으로 조회하시오. 1. 브라우저 요청 받기. controller/ArticleController @GetMapping("/articles") 이라는 URL로 받아온다. 2. 컨트롤러 처리 흐름 - 1. 모든 Article을 가져온다! - 2.

github.com

소스코드참고.

728x90