Spring/Spring boot icia 68일차

Spring boot 예제 만들기

swkn 2023. 5. 30. 16:17
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a href="/save">책 등록</a>
<a href="/books">책 목록</a>
</body>
</html>

인덱스에서 책 등록과 책 목록 페이지를 만들었다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    * {
        margin: 0;
    }

    iable {
        display: block;
    }

    input {
        display: block;
    }
</style>
<body>
        <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>
</body>
</html>

input 태그로 입력받고 DTO에 맞춰 name을 설정후 form 태그로 전송한다.

package com.example.book.DTO;

import lombok.Data;

@Data
public class BookDTO {
    private Long id;
    private String book_name;
    private String book_author;
    private int book_price;
}

 

package com.example.book.Entity;

import com.example.book.DTO.BookDTO;
import lombok.Data;

import javax.persistence.*;

@Entity
@Data
@Table(name = "book_table")
public class BookEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String bookName;

    @Column
    private String bookAuthor;

    @Column
    private int bookPrice;

    public static BookEntity toSaveEntity(BookDTO bookDTO) {
        BookEntity bookEntity = new BookEntity();
        bookEntity.setBookName(bookDTO.getBook_name());
        bookEntity.setBookAuthor(bookDTO.getBook_author());
        bookEntity.setBookPrice(bookDTO.getBook_price());
        return bookEntity;
    }
}

Entity를 private로 제약조건을 건후 toSaveEntity만 열어두어서 Service에서 데이터를 변환하는데 사용하는 메소드를 Public으로 제약조건을 건다.

    @PostMapping("/save")
    public String save(@ModelAttribute BookDTO bookDTO) {
        bookService.save(bookDTO);
        return "/index";
    }

Controller에서 Service로 넘긴다.

    public void save(BookDTO bookDTO) {
        BookEntity bookEntity = BookEntity.toSaveEntity(bookDTO);
        bookRepository.save(bookEntity);
    }

여기서 entity의 메소드가 사용되게 된다.

package com.example.book.Repository;

import com.example.book.Entity.BookEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<BookEntity,Long> {


}

Repository에서는 JpaRepository를 상속받기 때문에 각종 메소드를 사용할 수 있다.

그중에 데이터를 저장하기 위해 save를 사용한것이다.

메소드를 작동시키면 insert into 쿼리문으로 저장이 된다.

 

이제 출력을 하기 위해서는 리스트로 BookDTO를 받아와야 한다.

    @GetMapping("/books")
    public String books(Model model) {
        List<BookDTO> bookDTOList = bookService.findByList();
        model.addAttribute("bookDTOList",bookDTOList);
        return "/bookList";
    }

Service에서 Entity를 DTO로 변환시켜야 한다.

    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;
    }

bookDTO에서 public으로 메소드를 만든다.

    public List<BookDTO> findByList() {
        List<BookEntity> bookEntityList = bookRepository.findAll();
        List<BookDTO> bookDTOList = new ArrayList<>();
        for (int i = 0; i < bookEntityList.size(); i++) {
            BookDTO bookDTO = BookDTO.toListEntity(bookEntityList.get(i));
            bookDTOList.add(bookDTO);
        }
        return bookDTOList;
    }

Entity를 DTO로 변환시킨후에

<!DOCTYPE html>
<html lang="en" xmlns::th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <title>Title</title>

</head>
<body>
<div class="container2" style="margin: 0 auto; width: 100%; height: 70%">
    <div id="book-list" style="width: 80%; margin: 0 auto; height: auto; text-align: center;">
        <h2 style="margin-top: 100px">책 목록</h2><br>
        <ul class="nav" style="text-align: center; display: flex; justify-content: center;">
            <li class="nav-item" id="button">
                <button class="btn btn-primary" onclick="bookListInterface()">책 목록 확인</button>
            </li>
        </ul>
    </div>
    <div id="container" style="display: none">
        <table class="table table-dark table-striped">
            <tr>
                <th>id</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>
            </tr>
        </table>
        <button class="btn btn-dark" onclick="closeData()">닫기</button>
    </div>
</div>
</body>
<script>
    const bookListInterface = () => {
        const container = document.getElementById("container");
        const button = document.getElementById("button");
        container.style.display="block";
        button.style.display="none";
    }
    const closeData = () => {
        const container = document.getElementById("container");
        const button = document.getElementById("button");
        container.style.display="none";
        button.style.display="block";
    }
</script>
</html>

Html에서 코드를 작성한다.

목록을 작성했다.