개인프로젝트-02

이동원·2024년 7월 3일

카테고리 생성하기


@Entity
@Getter
@Setter
public class Category {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "category" , cascade = CascadeType.REMOVE)
    private List<Product> productList;
}



@Entity
@Getter
@Setter
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private double price; //상품 가격  - 소수도 표현 위해 double 변수 타입 설정.

    private String description; //상품 설명

    @ManyToOne
    private Category category;


}

public interface CategoryRepository  extends JpaRepository<Category ,Long> {
}


public interface ProductRepository extends JpaRepository<Product ,Long> {
    List<Product> findByCategory(Category category);
}

@Service
@RequiredArgsConstructor
public class CategoryService {

    private final CategoryRepository categoryRepository;

    //카테고리 목록 보여주기
    public List<Category> getCategoryList(){
    return categoryRepository.findAll();
    }

    //카테고리 아이디로 상세보기
    public Category getCategoryById(@PathVariable("id") Long id){
        return categoryRepository.findById(id).orElseThrow();
    }

    //카테고리 생성하기
    public Category createCategory(@RequestParam String name){
        Category category = new Category();
        category.setName(name);
       return categoryRepository.save(category);

    }

    // 카테고리 삭제하기
    public void deleteCategory(@PathVariable("id") Long id){
        categoryRepository.deleteById(id);
    }


}


@Service
@RequiredArgsConstructor
public class ProductService {

    private final ProductRepository productRepository;
    private final CategoryRepository categoryRepository;


    //상품리스트 보여주기
    public List<Product> getProductList() {
        return productRepository.findAll();
    }

    //상품 아이디로 찾아 상세보기하기
    public Product showProductById(@PathVariable("id") Long id) {
        return productRepository.findById(id).orElseThrow();
    }

    //상품 생성하기
    public Product createProduct(@RequestParam String name, @RequestParam String description, @RequestParam double price , @RequestParam Long categoryId) {

        Product product = new Product();
        product.setName(name);
        product.setDescription(description);
        product.setPrice(price);

        // 카테고리 연결하기
        Category category =categoryRepository.findById(categoryId).get(); //이미 카테고리는 존재한다.
        product.setCategory(category);
        category.getProductList().add(product); // List 는 ArrayList 니깐 add 를해준다.


        return productRepository.save(product);



    }
    // 상품 삭제하기
    public void deleteProduct(@PathVariable("id") Long id){
        productRepository.deleteById(id);
    }

     // 카테고리별 상품 찾기
    public List<Product> getProductByCategory(Category category){
        return productRepository.findByCategory(category);
    }
}



@Controller
@RequiredArgsConstructor
@RequestMapping("/category")
public class CategoryController {
    private final CategoryService categoryService;
    private final ProductService productService;


    //카테고리 리스트 보여주기
    @GetMapping("/list")
    public String getCategoryList(Model model){
        List<Category> categoryList = categoryService.getCategoryList();
        model.addAttribute("categoryList" , categoryList);
        return "category_list";
    }

    //카테고리 아이디로 상세보기
    @GetMapping("/{id}")  // @PathVariable  이름하고 같아야한다 .
    public String getCategoryById(@PathVariable("id") Long categoryId, Model model) {
        Category category = categoryService.getCategoryById(categoryId);
        // 카테고리의 제품 목록을 모델에 추가 (가정)
        List<Product> productList = productService.getProductByCategory(category);
        model.addAttribute("productList", productList);
        return "category_detail";
    }

    //카테고리 생성 폼
    @GetMapping("/create")
    public String createCategory(){
        return "category_form";
    }

    //카테고리 생성하기
    @PostMapping("/create")
    public String createCategory(@RequestParam String name){
        categoryService.createCategory(name);
        return "redirect:/category/list";
    }

    // 카테고리 삭제 폼

    @GetMapping("/delete")
    public String deleteCategory(){
        return "category_delete";
    }

    //카테고리 삭제하기
    @PostMapping("/delete")
    public String deleteCategory(@RequestParam Long categoryId){
        categoryService.deleteCategory(categoryId);
        return "redirect:/category/list";
    }


}

<!--product_list-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>리스트</title><!-- 위에 페이지 이름 지정해줌 -->

</head>

<body>
<h2>카테고리 리스트</h2>
<ul>
    <li th:each="category : ${categoryList}">
        <a th:href="@{|/category/${category.id}|}">
            <span th:text="${category.name}"></span>
        </a>
    </li>
</ul>

<div><a th:href="@{/category/create}">카테고리 생성</a></div>
<div><a th:href="@{/category/delete}">카테고리 삭제</a></div>

<h2>상품 리스트</h2>

<ul>
    <li th:each="product : ${productList}">
        <a th:href="@{|/product/${product.id}|}"> <!--  경로에 변수 넣을때는 @{||}-->
        <span th:text="${product.name}"></span>
        <span th:text="${product.price}"></span>
        </a>
    </li>
</ul>
<div><a th:href="@{/product/create}">상품 생성</a></div>
<div><a th:href="@{/product/delete}">상품 삭제</a></div>



</body>
</html>

<!--category_delete-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>카테고리 삭제하기</title>
</head>
<body>
<h2>카테고리 삭제하기</h2>

<form th:action="@{/category/delete}" method="post">
    <label for="categoryId">삭제할 카테고리 아이디:</label><br>
    <input type="text" name="categoryId" id="categoryId">
    <input type="submit" value="카테고리 삭제">
</form>

</body>
</html>

<!--category_form-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>카테고리 생성</title>
</head>
<body>
<h2>카테고리 생성</h2>
<form th:action="@{/category/create}" method="post">
    <label for="name">카테고리 이름: </label><br>
    <input type="text" id="name" name="name" placeholder="카테고리 이름">
    <input type="submit" value="카테고리 생성">
</form>

</body>
</html>

<!--category_list-->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>카테고리 리스트</title>
</head>
<body>
<h2>카테고리 리스트</h2>

<ul>
    <li th:each="category :${categoryList}">
        <a th:href="@{|/category/${category.id}|}">
        <span th:text="${category.name}"></span>
        </a>
    </li>
</ul>
<div><a th:href="@{/category/create}">카테고리 생성</a></div>
<div><a th:href="@{/category/delete}">카테고리 삭제</a></div>



</body>
</html>

<!--category_detail-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>카테고리 상세보기</title>
</head>
<body>
<h2>카테고리 상세보기</h2>
<ul>
    <li th:each="product : ${productList}">
        <div>
        <span th:text="${product.name}"></span>
        <span th:text="${product.price}"></span>
        <span th:text="${product.description}"></span>
        </div>
    </li>
</ul>


</body>
</html>

0개의 댓글