package com.shop.shop.dto;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Getter
@Setter
public class CartItemDto {
@NotNull(message = "상품 아이디는 필수 입력 값 입니다.")
private Long itemId;
@Min(value = 1, message = "최소 1개이상 담아주세요")
private int count;
}
public static Cart createCart(Member member){
Cart cart = new Cart();
cart.setMember(member);
return cart;
}
public static CartItem createCartItem (Cart cart, Item item, int count){
CartItem cartItem = new CartItem();
cartItem.setCart(cart);
cartItem.setItem(item);
cartItem.setCount(count);
return cartItem;
}
public void addCount(int count){
this.count += count;
}
package com.shop.shop.repository;
import com.shop.shop.entity.Cart;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CartRepository extends JpaRepository<Cart, Long> {
Cart findByMemberId(Long memberId);
}
package com.shop.shop.repository;
import com.shop.shop.entity.CartItem;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CartItemRepository extends JpaRepository<CartItem, Long> {
CartItem findByCartIdAndItemId(Long cartId, Long itemId);
}
package com.shop.shop.service;
import com.shop.shop.dto.CartItemDto;
import com.shop.shop.entity.Cart;
import com.shop.shop.entity.CartItem;
import com.shop.shop.entity.Item;
import com.shop.shop.entity.Member;
import com.shop.shop.repository.CartItemRepository;
import com.shop.shop.repository.CartRepository;
import com.shop.shop.repository.ItemRepository;
import com.shop.shop.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityNotFoundException;
@Service
@RequiredArgsConstructor
@Transactional
public class CartService {
private final ItemRepository itemRepository;
private final MemberRepository memberRepository;
private final CartRepository cartRepository;
private final CartItemRepository cartItemRepository;
public Long addCart(CartItemDto cartItemDto,String email){
Item item = itemRepository.findById(cartItemDto.getItemId())
.orElseThrow(EntityNotFoundException::new);
Member member = memberRepository.findByEmail(email);
Cart cart = cartRepository.findByMemberId(member.getId());
if (cart == null){
cart = Cart.createCart(member);
cartRepository.save(cart);
}
CartItem savedCartItem =
cartItemRepository.findByCartIdAndItemId(cart.getId(),item.getId());
if (savedCartItem != null){ //장바구니에 기존 상품이 있을 경우
savedCartItem.addCount(cartItemDto.getCount());
return savedCartItem.getId();
}else {
CartItem cartItem= CartItem.createCartItem(cart, item, cartItemDto.getCount());
cartItemRepository.save(cartItem);
return cartItem.getId();
}
}
}
package com.shop.shop.controller;
import com.shop.shop.dto.CartItemDto;
import com.shop.shop.service.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
import java.security.Principal;
import java.util.List;
@Controller
@RequiredArgsConstructor
public class CartController {
private final CartService cartService;
@PostMapping(value = "/cart")
public @ResponseBody ResponseEntity order(@RequestBody @Valid CartItemDto cartItemDto,
BindingResult bindingResult, Principal principal) {
if (bindingResult.hasErrors()) {
StringBuilder sb = new StringBuilder();
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
sb.append(fieldError.getDefaultMessage());
}
return new ResponseEntity<String>(sb.toString(), HttpStatus.BAD_REQUEST);
}
String email = principal.getName();
Long cartItemId;
try {
cartItemId = cartService.addCart(cartItemDto,email);
}catch (Exception e){
return new ResponseEntity<String>(e.getMessage(),HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Long>(cartItemId, HttpStatus.OK);
}
}
package com.shop.shop.dto;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class CartDetailDto {
//hiden값으로 들어가짐 꼭 필요
private Long cartItemId;
private String itemNm;
private int price;
private int count;
private String imgUrl;
public CartDetailDto(Long cartItemId, String itemNm, int price, int count, String imgUrl) {
this.cartItemId = cartItemId;
this.itemNm = itemNm;
this.price = price;
this.count = count;
this.imgUrl = imgUrl;
}
}
package com.shop.shop.repository;
import com.shop.shop.dto.CartDetailDto;
import com.shop.shop.entity.CartItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface CartItemRepository extends JpaRepository<CartItem, Long> {
CartItem findByCartIdAndItemId(Long cartId, Long itemId);
@Query("select new com.shop.shop.dto.CartDetailDto(ci.id, i.itemNm, i.price, ci.count, im.imgUrl) " +
"from CartItem ci, ItemImg im " +
"join ci.item i " +
"where ci.cart.id = :cartId " +
"and im.item.id = ci.item.id " +
"and im.repimgYn = 'Y' " +
"order by ci.regTime desc"
)
List<CartDetailDto> findCartDetailDtoList(Long cartId);
}
CartDetailDto 생성자를 이용하여 DTO를 반환할 때 "new com.shop.dto.CartDetailDto"처럼 new 키워드와 해당 Dto의 패키지, 클래스명을 적어줍니다. 또한 생성자의 파라미터 순서는 DTO 클래스에 명시한 순으로 넣어주어야 합니다.
@Transactional(readOnly = true)
public List<CartDetailDto> getCartList(String email){
List<CartDetailDto> cartDetailDtoList = new ArrayList<>();
Member member = memberRepository.findByEmail(email);
Cart cart = cartRepository.findByMemberId(member.getId());
if (cart == null){
return cartDetailDtoList;
}
cartDetailDtoList =
cartItemRepository.findCartDetailDtoList(cart.getId());
return cartDetailDtoList;
}
@GetMapping(value = "/cart")
public String orderHist(Principal principal, Model model) {
List<CartDetailDto> cartDetailist =
cartService.getCartList(principal.getName());
model.addAttribute("cartItems",cartDetailist);
return "cart/cartList";
}