@GeneratedValue(strategy = GenerationType.IDENTITY) : DB에 맡기기
(AutoIncrement check)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
(AutoIncrement에 check가 안되고 hibernate_sequence table에 insert)
private final ArticleRepository articleRepository;
public ArticleController(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
ArticleController
@GetMapping(value = "/{id}")
public String selectSingle(@PathVariable Long id, Model model) {
Optional<Article> optArticle = articleRepository.findById(id);
if(!optArticle.isEmpty()){
model.addAttribute("article", optArticle.get());
return "articles/show";
} else {
return "articles/error";
}
}
🔸 @PathVariable로 id값 가져오기 (붙어있는 변수와 같은 {}안의 값을 가져옴)
🔸 findById(id) : id에 해당하는 데이터 조회
🔸 Optional<Article>
: Article객체 or Null을 담을 수 있음
👉 DB에 id에 해당하는 데이터가 있다면 넣고, 없다면 Null 넣기
🔸 Article이 담겼다면 show
페이지의 article 값에 넣고 이동, Null이라면 error
페이지로 이동
(아래 show
페이지의 {{변수}}
에 각 변수의 값이 들어감)
show.mustache
{{>layouts/header}}
<div class="card" style="width: 18rem;">
{{#article}}
<div class="card-body">
<h5 class="card-title">{{id}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{title}}</h6>
<p class="card-text">{{content}}</p>
<a href="/articles/new" class="card-link">new article</a>
<a href="/articles" class="card-link">articles List</a>
</div>
{{/article}}
</div>
{{>layouts/footer}}
error.mustache
<div>
이 페이지는 error page입니다.
</div>
@PostMapping(value = "/posts")
public String createArticle(ArticleDto form) {
log.info(form.toString());
Article article = form.toEntity();
Article savedArticle = articleRepository.save(article);
return String.format("redirect:/articles/%d", savedArticle.getId());
}
🔴 redirect 활용 : 해당 주소로 이동
👉 해당 코드에서는 저장한 id를 주소에 넣어 해당 id를 조회하도록 함.
ArticleController
@GetMapping("/list")
public String list(Model model) {
List<Article> articles = articleRepository.findAll();
model.addAttribute("articles", articles);
return "articles/list";
}
@GetMapping("")
public String index() {
return "redirect:/articles/list";
}
🔸 findAll()을 활용하여 전체 데이터 조회
🔸 articles에 전체 데이터를 넣고 list로 보냄
🔸 "/articles"에 접속한다면 자동으로 "/articles/list"으로 이동하도록 redirect
(여기에서 앞에 /articles가 붙는 이유는 클래스 상단에 @RequestMapping("/articles")
를 붙여줬기 때문)
list.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 class="table-group-divider">
{{#articles}}
<tr>
<th>{{id}}</th>
<td><a href="/articles/{{id}}">{{title}}</a></td>
<td>{{content}}</td>
</tr>
{{/articles}}
</tbody>
</table>
<a href="/articles/new">new article</a>
<a href="/articles">articles List</a>
{{>layouts/footer}}
🔴 List와 같은 collection 타입은 반복문으로 동작하여 tr부분이 데이터 개수만큼 반복됨