책 정보 수정 (1)
HomeController
@GetMapping("/modify/{id}")
public String modify(@PathVariable Long id, Model model){
Book book = bookService.findById(id);
model.addAttribute("book", book);
return "modify";
}
modify.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>modify</title>
</head>
<body>
<h3>책 수정</h3>
<form th:action="@{/modify}" method="post">
<input type="hidden" name="id" th:value="${book.id}">
<table border="1">
<tr>
<td>번호</td>
<td th:text="${book.id}">ID</td>
</tr>
<tr>
<td>제목</td>
<td><input type="text" name="title" th:value="${book.title}"/></td>
</tr>
<tr>
<td>가격</td>
<td><input type="number" name="price" th:value="${book.price}"/></td>
</tr>
<tr>
<td>저자</td>
<td><input type="text" name="author" th:value="${book.author}"/></td>
</tr>
<tr>
<td>페이지</td>
<td><input type="number" name="page" th:value="${book.page}"/></td>
</tr>
<tr>
<td colspan="2">
<button type="submit">수정</button>
<button type="reset">취소</button>
</td>
</tr>
</table>
</form>
</body>
</html>
BookService
public Book update(Book book){
Optional<Book> optional=bookRepository.findById(book.getId());
if(optional.isPresent()){
Book dbbook=optional.get();
dbbook.setTitle(book.getTitle());
dbbook.setPrice(book.getPrice());
dbbook.setAuthor(book.getAuthor());
dbbook.setPage(book.getPage());
bookRepository.save(dbbook);
return dbbook;
}else{
throw new RuntimeException("Book not found with id:"+book.getId());
}
}
HomeController
@PostMapping("/modify")
public String modify(Book book){
bookService.update(book);
return "redirect:/list";
}
책 정보 수정 (2)
BookService
public Book update(Long id, Book book){
Optional<Book> optional=bookRepository.findById(id);
if(optional.isPresent()){
Book dbbook=optional.get();
dbbook.setTitle(book.getTitle());
dbbook.setPrice(book.getPrice());
dbbook.setAuthor(book.getAuthor());
dbbook.setPage(book.getPage());
bookRepository.save(dbbook);
return dbbook;
}else{
throw new RuntimeException("Book not found with id:"+id);
}
}
HomeController
@PostMapping("/modify/{id}")
public String modify(@PathVariable Long id, Book book){
bookService.update(id, book);
return "redirect:/list";
}
modify.html
- hidden 지우기
- id pathvarible로 넘기기
<h3>책 수정</h3>
<form th:action="@{/modify/{id}(id=${book.id})}" method="post">
BookService
save 지워도 더티체킹을 통해 수정이 가능하다
Transactional annotation 필수!!
@Transactional
public Book update(Long id, Book book){
Optional<Book> optional=bookRepository.findById(id);
if(optional.isPresent()){
Book dbbook=optional.get();
dbbook.setTitle(book.getTitle());
dbbook.setPrice(book.getPrice());
dbbook.setAuthor(book.getAuthor());
dbbook.setPage(book.getPage());
return dbbook;
}else{
throw new RuntimeException("Book not found with id:"+id);
}
}