数据库设计
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());}
}