添加购物车功能

发布于:2025-04-05 ⋅ 阅读:(12) ⋅ 点赞:(0)

业务需求:

用户提交三个字段,服务端根据提交的字段判断是菜品还是套餐,根据菜品或者套餐添加购物车表中。

代码实现


@RestController
@Slf4j
@RequestMapping("/user/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private 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 {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    public 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.插入商品时,判断是菜品还是套餐。
    }
}

 


网站公告

今日签到

点亮在社区的每一天
去签到