业务需求:
用户提交三个字段,服务端根据提交的字段判断是菜品还是套餐,根据菜品或者套餐添加购物车表中。
代码实现
@RestController
@Slf4j
@RequestMapping("/user/shoppingCart")
public class ShoppingCartController {@Autowiredprivate ShoppingCartService shoppingCartService;@PostMapping("/add")public Result addShoppingCart(@RequestBody ShoppingCartDTO shoppingCartDTO){log.info("添加购物车参数:{}",shoppingCartDTO);shoppingCartService.addShoppingCart(shoppingCartDTO);return Result.success();}
}
实现类
@Slf4j
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {@Autowiredprivate ShoppingCartMapper shoppingCartMapper;@Autowiredprivate DishMapper dishMapper;@Autowiredprivate SetmealMapper setmealMapper;@Overridepublic void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {//1.先构造一个shoppingcart对象ShoppingCart shoppingCart = new ShoppingCart();BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);Long userId = BaseContext.getCurrentId();shoppingCart.setUserId(userId);List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);//2.查询这个用户的购物车中有没有这个对象,如果有那么number数量加1,如果没有那么插入这个商品if (list != null && list.size()>0){ShoppingCart shoppingcart = list.get(0);shoppingcart.setNumber(shoppingcart.getNumber()+1);shoppingCartMapper.update(shoppingcart);}else {//3.如果没有那么插入商品时,判断是菜品还是套餐。Long dishId = shoppingCartDTO.getDishId();if (dishId != null){//如果dishId不为空,说明是菜品,那么插入菜品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);}//3.插入商品时,判断是菜品还是套餐。}
}