ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 쇼핑몰 프로젝트 --아이템 리뷰 등록, 조회, 수정, 삭제(api)
    쇼핑몰 프로젝트 2024. 6. 15. 13:50

     

     

    itemReviewRepository

    package ypjs.project.repository;
    
    import jakarta.persistence.EntityManager;
    import lombok.RequiredArgsConstructor;
    import org.springframework.stereotype.Repository;
    import ypjs.project.domain.ItemReview;
    
    import java.util.List;
    
    @Repository
    @RequiredArgsConstructor
    public class ItemReviewRepository {
    
        private final EntityManager em;
    
    
        //리뷰저장
        public void saveReview(ItemReview itemReview) {
                em.persist(itemReview);
        }
    
    
        //리뷰 하나 조회
        public ItemReview findOneReview(Long itemReviewId) {
            return em.find(ItemReview.class, itemReviewId);
        }
    
    
    
        //리뷰 삭제
        public void deleteItemReview(Long itemReviewId) {
            ItemReview findItemReivew = em.find(ItemReview.class, itemReviewId);
            em.remove(findItemReivew);
        }
    
    
        //아이템 당 리뷰 조회 (페치조인 안한것)
    //    public List<ItemReview> findAllItemReview(Long itemId) {
    //       return em.createQuery("select ir from ItemReview ir WHERE ir.item.itemId = :itemId", ItemReview.class)
    //                .setParameter("itemId", itemId)
    //                .getResultList();
    //    }
    
        //페치조인 (아이템 당 리뷰 조회)
        public List<ItemReview> findAllItemReview(Long itemId) {
            return em.createQuery(
                            "select ir from ItemReview ir" +
                                   " join fetch ir.item i WHERE i.itemId = :itemId", ItemReview.class)
                    .setParameter("itemId", itemId)
                    .getResultList();
        }
    
    
    }

     

     

     

    itemReviewService

    @Service
    @Transactional(readOnly = true)
    @RequiredArgsConstructor
    public class ItemReviewService {
    
        private final ItemReviewRepository itemReviewRepository;
        private final ItemRepository itemRepository;
        private final MemberRepository memberRepository;
    
    
        //리뷰등록
        @Transactional
        public ItemReview saveItemReview(ItemReviewDto itemReviewDto) {
            Item item = itemRepository.findOne(itemReviewDto.getItemId());
            Member member = memberRepository.findOne(itemReviewDto.getMemberId());
    
    
            ItemReview itemReview = new ItemReview(
                    item,
                    member,
                    itemReviewDto.getItemScore(),
                    itemReviewDto.getItemReviewName(),
                    itemReviewDto.getItemReviewContent()
            );
    
            //리뷰 저장
            itemReviewRepository.saveReview(itemReview);
    
            // 새로운 리뷰가 추가된 후 아이템의 리뷰 리스트를 업데이트
            item.getItemReviews().add(itemReview);
    
            //평점 업데이트
            item.updateItemRatings();
    
            itemRepository.saveItem(item);
    
    
            return itemReview;
        }
    
    
        //리뷰조회
        public ItemReview findOneItemReview(Long itemReviewId) {
            return itemReviewRepository.findOneReview(itemReviewId);
        }
    
    
        //아이템 당 리뷰조회
        public List<ItemReviewListDto> findAllItemReview(Long itemId) {
            //List<ItemReview> reviews = itemReviewRepository.findAllItemReview(itemId);
            List<ItemReview> reviews = itemReviewRepository.findAllItemReview(itemId);
    
            List<ItemReviewListDto> result = reviews.stream()
                    .map(ItemReviewListDto::new)
                    .collect(Collectors.toList());
    
            return result;
        }

     

     

    itemReviewDto

    package ypjs.project.dto.itemdto;
    
    import lombok.Getter;
    
    @Getter
    public class ItemReviewDto {
    
        private Long itemId;
        private Long memberId;
        private int itemScore;
        private String itemReviewName;
        private String itemReviewContent;
    
    
        public ItemReviewDto() {}
    
    
        public ItemReviewDto(Long itemId, Long memberId, int itemScore, String itemReviewName, String itemReviewContent) {
            this.itemId = itemId;
            this.memberId = memberId;
            this.itemScore = itemScore;
            this.itemReviewName = itemReviewName;
            this.itemReviewContent = itemReviewContent;
        }
    
    
    
    
    }
    

     

     

    ItemOneDto

    package ypjs.project.dto.itemdto;
    
    import lombok.Getter;
    import ypjs.project.domain.Item;
    
    import java.util.List;
    import java.util.stream.Collectors;
    
    @Getter
    public class ItemOneDto {
    
        private String itemName;
        private String itemContent;
        private int itemPrice;
        private double itemRatings;
    
        private List<ItemReviewListDto> itemReviews;
    
    
        public ItemOneDto() {
        }
    
        public ItemOneDto(Item item) {
    
    
            itemName = item.getItemName();
            itemContent = item.getItemContent();
            itemPrice = item.getItemPrice();
            itemRatings = item.getItemRatings();
    
            itemReviews = item.getItemReviews().stream()
                    .map(itemReview -> new ItemReviewListDto(itemReview))
                    .collect(Collectors.toList());
    
        }
    
    
    }
    
    
    
    
    
    
    
    

     

     

    ItemReviewListDto

    package ypjs.project.dto.itemdto;
    
    import lombok.Getter;
    import ypjs.project.domain.Item;
    import ypjs.project.domain.ItemReview;
    
    import java.util.List;
    import java.util.stream.Collectors;
    
    @Getter
    public class ItemReviewListDto {
    
        Long itemId;
        // String nickname;
        private int itemScore;
        private String itemReviewName;
        private String itemReviewContent;
    
    
        public ItemReviewListDto() {}
    
        public ItemReviewListDto(ItemReview itemReview) {
    
            itemId = itemReview.getItem().getItemId();
            // nickname = itemReview.getMember().getNickname();
            itemScore = itemReview.getItemScore();
            itemReviewName = itemReview.getItemReviewName();
            itemReviewContent = itemReview.getItemReviewContent();
    
    
        }
    
    
    
    
    
    }
    

     

     

    평점계산

    Item클래스

    //평점계산
    public void updateItemRatings() {
    
        if (itemReviews == null || itemReviews.isEmpty()) {
            this.itemRatings = 0;
        }
    
        double totalScore = 0;
        int count = 0; // 평가된 리뷰의 개수를 세기 위한 변수
        for (ItemReview review : itemReviews) {
            if (review.getItemScore() != 0) {
                //double score = Math.min(Math.max(review.getItemScore(), 1.0), 5.0);
                //totalScore += score;
                totalScore += review.getItemScore();
                count++;
            }
        }
        if (count > 0) {
            double averageScore = totalScore / count;
            // 소숫점 첫째자리까지 반환
            this.itemRatings = Math.round(averageScore * 10.0) / 10.0; //소숫점 첫째자리까지 반환
        } else {
            this.itemRatings = 0;
        }
    
    }
    

     

     

    itemReviewController

    @RestController
    @RequiredArgsConstructor
    public class ItemReviewController {
    
        private final ItemReviewService itemReviewService;
        private final ItemService itemService;
    
    
    
        //리뷰등록
        @PostMapping("/ypjs/itemReview/post/{itemId}")
        public ItemReviewDto saveItemReview(@PathVariable("itemId") Long itemId,
                                            @RequestBody @Valid ItemReviewDto requestDto) {
    
            itemService.findOneItem(itemId);
            ItemReview itemReview = itemReviewService.saveItemReview(requestDto);
    
            return new ItemReviewDto(itemReview.getItem().getItemId(), itemReview.getMember().getMemberId(), itemReview.getItemScore(), itemReview.getItemReviewName(), itemReview.getItemReviewContent());
        }
    

     

    아이템 당 리뷰 조회는 앞에 올렸던 아이템 컨트롤러에 있음

     

     

     

    아이템리뷰 수정, 삭제

    itemReview클래스(변경감지메서드 추가)

    //리뷰변경 메서드
    public Long changeItemReview(Item item,Member member, int itemScore, String itemReviewName, String itemReviewContent) {
        this.item = item;
        this.member = member;
        this.itemScore = itemScore;
        this.itemReviewName = itemReviewName;
        this.itemReviewContent = itemReviewContent;
    
        return this.itemReviewId;
    }
    

     

     

    itemReviewService(변경감지 메서드 추가)

    //수정
    @Transactional
    public void updateItemReview(Long itemReviewId, ItemReviewDto itemReviewDto) {
    
        ItemReview itemReview = itemReviewRepository.findOneReview(itemReviewId);
    
        if (itemReview == null) {
            throw new IllegalArgumentException("ItemReview not found with id: " + itemReviewId);
        }
    
        Item item = itemRepository.findOne(itemReviewDto.getItemId());
        Member member = memberRepository.findOne(itemReviewDto.getMemberId());
    
        itemReview.changeItemReview(
                item,
                member,
                itemReviewDto.getItemScore(),
                itemReviewDto.getItemReviewName(),
                itemReviewDto.getItemReviewContent()
        );
    
        // 새로운 리뷰가 추가된 후 아이템의 리뷰 리스트를 업데이트
        item.getItemReviews().add(itemReview);
    
        //평점 업데이트
        item.updateItemRatings();
    
        itemRepository.saveItem(item);
    }
    
    
    
    //리뷰 삭제
    @Transactional
    public void deleteItemReview(Long itemReviewId) {
        ItemReview itemReview = findOneItemReview(itemReviewId);
        Item item = itemReview.getItem();
    
        itemReviewRepository.deleteItemReview(itemReviewId);
    
        item.removeItemReview(itemReview);
    
        item.updateItemRatings();
    
    
    
    
    }
    

     

     

    itemReviewController

    //수정
    @PutMapping("/ypjs/itemReview/update/{itemReviewId}")
    public ItemReviewDto updateItemReview(@PathVariable("itemReviewId") Long itemReviewId,
                                          @RequestBody @Valid ItemReviewDto itemReviewDto) {
    
        itemReviewService.updateItemReview(itemReviewId, itemReviewDto);
        ItemReview findItemReview = itemReviewService.findOneItemReview(itemReviewId);
    
        return new ItemReviewDto(findItemReview.getItem().getItemId(), findItemReview.getMember().getMemberId(), findItemReview.getItemScore(), findItemReview.getItemReviewName(), findItemReview.getItemReviewContent());
    }
    
    
    //삭제
    @DeleteMapping("/ypjs/itemReview/delete/{itemReviewId}")
    public void deleteItemReview(@PathVariable("itemReviewId") Long itemReviewId){
        itemReviewService.deleteItemReview(itemReviewId);
    }
    

     

     

     

    api기반 파일

    YPJS.zip
    0.57MB

Designed by Tistory.