购物车相关接口
添加购物车,购物车列表,更新商品数量,删除购物车
先新建CartController和CartService,还有两个vo对象,一个是购物车Vo,还有一个是购物车itemVo
public class CartVo {
private List<CartProductVo> cartProductVoList;//购物车itemList
private BigDecimal cartTotalPrice;
private Boolean allChecked;//是否已经都勾选
private String imageHost;
//省略get和set
}
public class CartProductVo {
//结合了产品和购物车的一个抽象对象
private Integer id;
private Integer userId;
private Integer productId;
private Integer quantity;//购物车中此商品的数量
private String productName;
private String productSubtitle;
private String productMainImage;
private BigDecimal productPrice;
private Integer productStatus;
private BigDecimal productTotalPrice;
private Integer productStock;
private Integer productChecked;//此商品是否勾选
private String limitQuantity;//限制数量的一个返回结果
//省略get和set
}
添加购物车
在Service里新建add方法,传3个参数,userId, productId, count,用户id和商品id和数量,然后去购物车表里查找一下该商品,找不到就新增一个商品,找到了就增加它的数量。
public ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count){
if(productId == null || count == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
}
Cart cart = cartMapper.selectCartByUserIdProductId(userId,productId);
if(cart == null){
//这个产品不在这个购物车里,需要新增一个这个产品的记录
Cart cartItem = new Cart();
cartItem.setQuantity(count);
cartItem.setChecked(Const.Cart.CHECKED);
cartItem.setProductId(productId);
cartItem.setUserId(userId);
cartMapper.insert(cartItem);
}else{
//这个产品已经在购物车里了.
//如果产品已存在,数量相加
count = cart.getQuantity() + count;
cart.setQuantity(count);
cartMapper.updateByPrimaryKeySelective(cart);
}
return null;
}
Controller里新增add方法,然后判断是否登录
@RequestMapping("add.do")
@ResponseBody
public ServerResponse<CartVo> add(HttpSession session, Integer count, Integer productId){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
}
return iCartService.add(user.getId(),productId,count);
}
数字在计算的时候要避免精度丢失
会出现下不了单,或者对账对不齐等问题,通常用BigDecimal解决问题,用BigDecimal的构造器传入两个浮点数的字符串,如下:
所以可以封装一个工具类
public class BigDecimalUtil {
private BigDecimalUtil(){
}
public static BigDecimal add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2);
}
public static BigDecimal sub(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2);
}
public static BigDecimal mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2);
}
public static BigDecimal div(double v1,double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);//四舍五入,保留2位小数
//除不尽的情况
}
}
在增加数量得时候,如果请求的数量超过商品库存,就要相应的改成商品库存,例如购物车添加100个,库存只有50个,那么购物车只能添加50个
新建一个方法组装CartVo顺便判断一下库存
private CartVo getCartVoLimit(Integer userId){
CartVo cartVo = new CartVo();
List<Cart> cartList = cartMapper.selectCartByUserId(userId);
List<CartProductVo> 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;
}
private boolean getAllCheckedStatus(Integer userId){
if(userId == null){
return false;
}
return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
}
更新购物车数量
有了上面的基础,这个逻辑就不难了,在service新增update方法,验证是否存在,存在就更新
public ServerResponse<CartVo> update(Integer userId,Integer productId,Integer count){
if(productId == null || count == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
}
Cart cart = cartMapper.selectCartByUserIdProductId(userId,productId);
if(cart != null){
cart.setQuantity(count);
}
cartMapper.updateByPrimaryKey(cart);
return this.list(userId);
}
在Controller调用就可以了
删除购物车商品
在service新增deleteProduct方法,有可能一次删除多个商品,所以传参数的时候传一个商品id字符串用逗号分割成数组,用GUAVA的Splitter方法可以省去很多麻烦,否则要先分割成数组,再遍历数组然后一个个add进List
public ServerResponse<CartVo> deleteProduct(Integer userId,String productIds){
List<String> productList = Splitter.on(",").splitToList(productIds);
if(CollectionUtils.isEmpty(productList)){
return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
}
cartMapper.deleteByUserIdProductIds(userId,productList);
return this.list(userId);
}
mapper里的sql实现,遍历所有的productId删除
<delete id="deleteByUserIdProductIds" parameterType="map">
SELECT FROM mmall_cart
WHERE user_id = #{userId}
<if test="productIdList != null">
AND product_id IN
<foreach collection="productIdList" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</if>
</delete>
查询购物车
Service里新增list方法,controller调用就好
public ServerResponse<CartVo> list (Integer userId){
CartVo cartVo = this.getCartVoLimit(userId);
return ServerResponse.createBySuccess(cartVo);
}
全选,全反选,单选,单独反选
service层
public ServerResponse<CartVo> selectOrUnSelect (Integer userId,Integer productId,Integer checked){
cartMapper.checkedOrUncheckedProduct(userId,productId,checked);
return this.list(userId);
}
dao层
<update id="checkedOrUncheckedProduct" parameterType="map">
UPDATE mmall_cart
SET checked = #{checked},
update_time = now()
WHERE user_id = #{userId}
<if test="productId != null">
and product_id = #{productId}
</if>
</update>
controller层
@RequestMapping("select_all.do")
@ResponseBody
public ServerResponse<CartVo> selectAll(HttpSession session){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user ==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
}
return iCartService.selectOrUnSelect(user.getId(),null,Const.Cart.CHECKED);
}
@RequestMapping("un_select_all.do")
@ResponseBody
public ServerResponse<CartVo> unSelectAll(HttpSession session){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user ==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
}
return iCartService.selectOrUnSelect(user.getId(),null,Const.Cart.UN_CHECKED);
}
@RequestMapping("select.do")
@ResponseBody
public ServerResponse<CartVo> select(HttpSession session,Integer productId){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user ==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
}
return iCartService.selectOrUnSelect(user.getId(),productId,Const.Cart.CHECKED);
}
@RequestMapping("un_select.do")
@ResponseBody
public ServerResponse<CartVo> unSelect(HttpSession session,Integer productId){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user ==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
}
return iCartService.selectOrUnSelect(user.getId(),productId,Const.Cart.UN_CHECKED);
}
获取购物车数量
service层
public ServerResponse<Integer> getCartProductCount(Integer userId){
if(userId == null){
return ServerResponse.createBySuccess(0);
}
return ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId));
}
dao层
<select id="selectCartProductCount" parameterType="int" resultType="int">
select IFNULL(sum(quantity),0) as count from mmall_cart where user_id = #{userId}
</select>
controller层
@RequestMapping("get_cart_product_count.do")
@ResponseBody
public ServerResponse<Integer> getCartProductCount(HttpSession session){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user ==null){
return ServerResponse.createBySuccess(0);
}
return iCartService.getCartProductCount(user.getId());
}