
- 클라이언트가 URL 요청
- 서버의 컨트롤러 -> 해당 URL에서 찾으려는 데이터 정보를 리파지터리에 전달
- 리파지터리 -> DB에 데이터 조회 요청
- DB -> 해당 데이터를 엔티티로 변환
- 엔티티 -> 모델을 통해 뷰 템플릿으로 전달
- 뷰 페이지 화면에 출력
DB에 저장한 데이터를 웹 페이지에서 보기 위해 출력 페이지를 접속해야 함. -->> URL 요청!
게시글 1번 id 조회 -> localhost:8080/articles/1
게시글 2번 id 조회 -> localhost:8080/articles/2 로 접속하는 방법

@GetMapping("/articles/{id}") 어노테이션 작성@PathVariable 어노테이션 키워드 작성@Autowired 어노테이션을 작성함. Article articleEntity = articleRepository.findById(id).orElse(null);
- 위 코드 한 줄에서 DB에서 데이터를 가져옴과 동시에 데이터를 엔티티를 변환한다.
- Aritcle은 엔티티이고, articleEntity는 엔티티 객체.
해당 객체 안에 리파지터리.findById 메서드를 사용해 가져온 데이터를 넣음.
findById() : CrudRepository가 제공하는 메서드, 실제 반환형은 Optional<Article>Optional <Article>로 변경하거나, 위 코드처럼 맨 뒤에 .orElse(null)을 추가한다. .orElse(null)은 해당 id가 없으면 null을 반환하라는 뜻 public String show(@PathVariable Long id, Model model)
model.addAttribute("article",articleEntity);
return "/articles/show";
리턴 페이지를 /articles/show 로 지정 했으니 실제로 보여질 show 뷰 페이지를 만들자.
{{>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>
{{#article}}
<tr>
<th>{{id}}</th>
<td>{{title}}</td>
<td>{{content}}</td>
</tr>
{{/article}}
</tbody>
</table>
{{>layouts/footer}}
@NoArgsConstructor 어노테이션 추가. <웹 페이지에서 입력>

<로그 창>

<localhost:8080/articles/1 접속>

@GetMapping("/articles") // URL 요청 받기
public String index()성ex() 메서드 생성
return "";
}
Repository)findAll() 메서드 사용Article articleEntity = articleRepository.findById() 로 작성했지만List<Article> articleEntityList = articleRepository.findAll()DB에서 조회한 데이터 묶음을 리스트에 담긴 Article (엔티티) 타입으로 가져온다는 뜻
findAll() 메서드가 반환하는 데이터 타입은 Iterable이지만 현재 List 타입으로 데이터를 받고 있음.
- 다운캐스팅 (형변환)
findAll() 메서드가 반환하는 데이터 타입Iterable<Article>에서List<Article>로 다운캐스팅하기List<Article> articleEntityList = (List<Article>) articleRepository.findAll()
- 업캐스팅
articleEntityList의 타입을Iterable<Article>로 업캐스팅 하기Iterable<Article> articleEntityList = articleRepository.findAll()
- ArrayList 사용하기
ArticleRepository 파일에서 CrudRepository의 findAll() 메서드를 오버라이딩
해서 반환 타입을 ArrayList로 변경한다.
ArrayList<Article> articleEntityList = articleRepository.findAll()
@GetMapping("/articles")
public String index(Model model) {
ArrayList<Article> articleEntityList = articleRepository.findAll();
model.addAttribute("articleList", articleEntityList);
return "/articles/index";
}
}
{{>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}}
<실행 확인 하기>
/articles/new 페이지를 통해 3개의 데이터를 저장함.


데이터가 잘 저장되고 목록으로 잘 출력되는 것을 확인하였다!