數據庫設計
DTO設計
實現步驟
1 判斷當前加入購物車中的的商品是否已經存在了
2?如果已經存在 只需要將數量加一
3 如果不存在 插入一條購物車數據
4 判斷加到本次購物車的是菜品還是套餐
Impl代碼實現
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {@Autowiredprivate ShoppingCartMapper shoppingCartMapper;@Autowiredprivate DishMapper dishMapper;@Autowiredprivate SetmealMapper setmealMapper;/*** 添加購物車* @param shoppingCartDTO*/@Overridepublic void add(ShoppingCartDTO shoppingCartDTO) {//判斷當前加入購物車中的的商品是否已經存在了ShoppingCart shoppingCart = new ShoppingCart();BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);shoppingCart.setUserId(BaseContext.getCurrentId());List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);//如果已經存在 只需要將數量加一if (list!=null&&list.size()>0){ShoppingCart cart = list.get(0);cart.setNumber(cart.getNumber()+1);shoppingCartMapper.updateNumberById(cart);}else{//如果不存在 插入一條購物車數據//判斷加到本次購物車的是菜品還是套餐Long dishId = shoppingCartDTO.getDishId();if (dishId!=null){//添加到購物車的是菜品Dish dish = dishMapper.getById(dishId);shoppingCart.setName(dish.getName());shoppingCart.setImage(dish.getImage());shoppingCart.setAmount(dish.getPrice());}else{//添加到購物車的是套餐Long setmealId = shoppingCartDTO.getSetmealId();Setmeal setmeal = setmealMapper.getById(setmealId);shoppingCart.setName(setmeal.getName());shoppingCart.setImage(setmeal.getImage());shoppingCart.setAmount(setmeal.getPrice());}shoppingCart.setNumber(1);shoppingCart.setCreateTime(LocalDateTime.now());shoppingCartMapper.insert(shoppingCart);}}@Overridepublic List<ShoppingCart> showShoppingCart() {Long userId = BaseContext.getCurrentId();ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);return list;}@Overridepublic void clean() {shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());}
}