cart算法 java实现_Java Cart类代码示例

这段代码展示了如何在Java中使用Cart算法实现购物车功能。通过遍历购物车列表,获取每个商品的详细信息,并根据库存情况调整购买数量。同时,计算购物车总价和商品的限购状态,并更新数据库中购物车的数量。
摘要由CSDN通过智能技术生成

import com.mmall.pojo.Cart; //导入依赖的package包/类

private CartVo getCartVoLimit(Integer userId){

CartVo cartVo = new CartVo();

List cartList = cartMapper.selectCartByUserId(userId);

List cartProductVoList = Lists.newArrayList();

BigDecimal cartTotalPrice = new BigDecimal("0");

if(CollectionUtils.isNotEmpty(cartList)){

for(Cart cartItem : cartList){

CartProductVo cartProductVo = new CartProductVo();

cartProductVo.setId(cartItem.getId());

cartProductVo.setUserId(userId);

cartProductVo.setProductId(cartItem.getProductId());

Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());

if(product != null){

cartProductVo.setProductMainImage(product.getMainImage());

cartProductVo.setProductName(product.getName());

cartProductVo.setProductSubtitle(product.getSubtitle());

cartProductVo.setProductStatus(product.getStatus());

cartProductVo.setProductPrice(product.getPrice());

cartProductVo.setProductStock(product.getStock());

//判断库存

int buyLimitCount = 0;

if(product.getStock() >= cartItem.getQuantity()){

//库存充足的时候

buyLimitCount = cartItem.getQuantity();

cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);

}else{

buyLimitCount = product.getStock();

cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);

//购物车中更新有效库存

Cart cartForQuantity = new Cart();

cartForQuantity.setId(cartItem.getId());

cartForQuantity.setQuantity(buyLimitCount);

cartMapper.updateByPrimaryKeySelective(cartForQuantity);

}

cartProductVo.setQuantity(buyLimitCount);

//计算总价

cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(),cartProductVo.getQuantity()));

cartProductVo.setProductChecked(cartItem.getChecked());

//如果不判断是否有商品就进行添加购物车操作,会报空指针异常。

if(cartItem.getChecked() == Const.Cart.CHECKED){

//如果已经勾选,增加到整个的购物车总价中

cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(),cartProductVo.getProductTotalPrice().doubleValue());

}

cartProductVoList.add(cartProductVo);

}

}

}

cartVo.setCartTotalPrice(cartTotalPrice);

cartVo.setCartProductVoList(cartProductVoList);

cartVo.setAllChecked(this.getAllCheckedStatus(userId));

cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

return cartVo;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值