1. Create
<form action="/save" method="post">
<label for="book-name">책 제목
<input type="text" id="book-name" name="book_name" placeholder="책 제목">
</label>
<label for="book-author">책 저자
<input type="text" id="book-author" name="book_author" placeholder="책 저자">
</label>
<label for="book-price">책 가격
<input type="text" id="book-price" name="book_price" placeholder="책 가격">
</label>
<input type="submit" value="등록">
</form>
저장할 데이터 받기
@PostMapping("/save")
public String save(@ModelAttribute BookDTO bookDTO) {
bookService.save(bookDTO);
return "/index";
}
컨트롤러에서 서비스로 전송
public void save(BookDTO bookDTO) {
BookEntity bookEntity = BookEntity.toSaveEntity(bookDTO);
bookRepository.save(bookEntity);
}
Entity로 전송되어야 하기 때문에 DTO를 Entity로 변환하는 과정이 추가된다.
public static BookDTO toListEntity(BookEntity bookEntity) {
BookDTO bookDTO = new BookDTO();
bookDTO.setId(bookEntity.getId());
bookDTO.setBook_name(bookEntity.getBookName());
bookDTO.setBook_author(bookEntity.getBookAuthor());
bookDTO.setBook_price(bookEntity.getBookPrice());
return bookDTO;
}
2. Read
@GetMapping("/books")
public String books(Model model) {
List<BookDTO> bookDTOList = bookService.findAll();
model.addAttribute("bookDTOList",bookDTOList);
return "/bookList";
}
컨트롤러에서 List를 받을 준비를 한다.
public List<BookDTO> findAll() {
List<BookEntity> bookEntityList = bookRepository.findAll();
List<BookDTO> bookDTOList = new ArrayList<>();
// for (int i = 0; i < bookEntityList.size(); i++) {
for(BookEntity bookEntity: bookEntityList) {
bookDTOList.add(BookDTO.toListEntity(bookEntity));
}
return bookDTOList;
}
마찬가지로 Entity 객체로 오기 때문에 서비스에서 다시 변환해야한다.
<div id="container" style="display: none">
<table class="table table-dark table-striped">
<tr>
<th>id</th>
<th>책이름</th>
<th>책저자</th>
<th>책금액</th>
<th>조회</th>
<th>삭제</th>
</tr>
<tr th:each="list: ${bookDTOList}">
<td th:text="${list.id}"></td>
<td th:text="${list.book_name}"></td>
<td th:text="${list.book_author}"></td>
<td th:text="${list.book_price}"></td>
<td>
<a th:href="@{|/list/${list.id}|}">조회</a>
</td>
<td>
<a th:href="@{|/delete/${list.id}|}">삭제</a>
</td>
</tr>
</table>
th을 사용해서 데이터를 전송한다.
3. Update
update때는 Save와 같지만 id를 주게되면 update 가 되고 , id를 주지 않게 되면 save쿼리가 되게 된다.
4. Delete
delete 메소드를 사용해서 데이터를 삭제한다.
'Spring > Spring boot icia 69일차' 카테고리의 다른 글
Spring boot로 member 시스템 만들기 (0) | 2023.05.31 |
---|---|
Spring boot TestCode (0) | 2023.05.31 |
Spring boot에서 Bootstrap 사용하기 (0) | 2023.05.31 |