개인프로젝트-04

이동원·2024년 7월 9일

리뷰기능 추가하기

리뷰 엔티티 작성

@Entity
@Getter
@Setter
public class Review {

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

    private String content; //리뷰 내용

    private int rating; //리뷰 별점

    @ManyToOne //리뷰는 다 상품은 일 이라 관계 설정해주기
    private Product product;


}


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

    @OneToMany(mappedBy = "product" , cascade =  CascadeType.REMOVE) //리뷰와 연결
    private List<Review> reviewList;

}

리뷰 레포지토리 작성

public interface ReviewRepository extends JpaRepository<Review,Long> {

    List<Review> findByProduct(Product product);
    // product 와 관련된 모든 review 를 반환
}

리뷰 서비스 작성

@Service
@RequiredArgsConstructor
public class ReviewService {

    private final ReviewRepository reviewRepository;
    private final ProductRepository productRepository;



    //리뷰 아이디로 리뷰 찾기

    public Review getReviewById(@PathVariable("id") Long id){
      return reviewRepository.findById(id).get();
    }


    //리뷰 생성하기 , 상품 연결해주기
    public Review createReview(@RequestParam String content , @RequestParam int rating ,@RequestParam  Long productId){
        Review review = new Review();
        review.setContent(content);
        review.setRating(rating);

        Product product = productRepository.findById(productId).orElseThrow();
        review.setProduct(product);
        product.getReviewList().add(review);
        return reviewRepository.save(review);

    }
    //리뷰 삭제하기
    public void deleteReview(@RequestParam Long id){
        reviewRepository.deleteById(id);
    }


    //상품관련 리뷰리스트 찾기
    public List<Review> getReviewByProduct(Product product){
        return reviewRepository.findByProduct(product);
    }
}

리뷰 컨트롤러 작성

@Controller
@RequiredArgsConstructor
@RequestMapping("/review")
public class ReviewController {

    private final ReviewService reviewService;
    private final ProductService productService;




    //리뷰 생성 폼
    @GetMapping("/create/{productId}")
    public String createReview(Model model  ,@PathVariable Long productId) {
        model.addAttribute("productId" , productId);
        return "review_form";
    }


    //리뷰 생성하기
    @PostMapping("/create")
    public String createReview(@RequestParam String content, @RequestParam int rating, @RequestParam("productId") Long productId) {
        reviewService.createReview(content, rating, productId);
        return String.format("redirect:/product/%d", productId);
    }


    //리뷰 삭제하기
    @PostMapping("/delete/{reviewId}")
    public String deleteReview(@PathVariable Long reviewId){
        Long productId = reviewService.getReviewById(reviewId).getProduct().getId();
        reviewService.deleteReview(reviewId);
        return String.format("redirect:/product/%d", productId);
    }
}

리뷰 생성 폼 html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form th:action="@{/review/create}" method="post">
    <input type="hidden" name="productId" th:value="${productId}"/>
    <label for="content">리뷰 내용:</label><br>
    <textarea name="content" id="content" cols="30" rows="10"></textarea><br>
    <label for="rating">리뷰 평점:</label>
    <input type="number" name="rating" id="rating"  min="1" max="5"/><br>
    <input type="submit" value="리뷰 작성">
</form>
</body>
</html>

리뷰 삭제 html


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

    <form th:action="@{/review/delete}" method="post">
        <input type="hidden" name="productId" th:value="${productId}"/>
        <label for="reviewId">삭제할 리뷰 아이디:</label><br>
        <input type="text" name="reviewId" id="reviewId">
        <input type="submit" value="리뷰 삭제">
    </form>

</body>
</html>

상품 상세보기 html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>상품 상세보기</title>
</head>
<body>
<h2>상품 상세보기</h2>
<ul>
    <li th:each="product : ${productById}">
        <span th:text="${product.description}"></span>
    </li>
</ul>

<ul>
    <li th:each="review : ${reviewList}">
        <span th:text="${review.content}"></span>
        <span th:text="${review.rating}"></span>
<!--       <a th:href="@{|/review/delete/${productById.id}|}">리뷰 삭제하기</a>-->
        <form th:action="@{|/review/delete/${review.id}|}" method="post">
            <input type="submit" value="리뷰 삭제하기">
        </form>
    </li>
</ul>


<div> <a th:href="@{|/review/create/${productById.id}|}">리뷰 작성하기</a> </div>
<div> <a th:href="@{/product/list}">목록으로 돌아가기</a> </div>



</body>
</html>

0개의 댓글