购物车模块

购物车模块

1:创建购物车实体类

@TableName("sys_cart")
@Data   //自动生成get/set方法
@Accessors(chain = true)   //自动生成setter方法并且返回当前对象
public class Cart extends BasePojo{
@TableId
private Long id;
private Long userId;
private Long itemId;
private String itemTitle;
private String itemImage;
private Long itemPrice;
private Integer num;}

2:接口实现类

@Service    //注意 dubbo的注解
public class DubboCartServiceImpl implements DubboCartService {

//   public interface DubboCartService {

//  List<Cart> findCartListByUserId(Long userId);

//  void updateCartNum(Cart cart);

//  void deleteCart(Cart cart);

//  void insertCart(Cart cart);

//  }


@Autowired
private CartMapper cartMapper;

@Override
public List<Cart> findCartListByUserId(Long userId) {
QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>();
queryWrapper.eq("user_id", userId);
return cartMapper.selectList(queryWrapper);
}

 

/**
* sql:update tb_cart set num=#{num},updated=#{updated}
* where user_id=#{userId}
* and item_id = #{itemId}
*/
@Override
public void updateCartNum(Cart cart) {
Cart cartTemp = new Cart();
cartTemp.setNum(cart.getNum())
.setUpdated(new Date());
UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<Cart>();
updateWrapper.eq("user_id", cart.getUserId())
.eq("item_id", cart.getItemId());
cartMapper.update(cartTemp, updateWrapper);

}

@Override
public void deleteCart(Cart cart) {
cartMapper.delete(new QueryWrapper<Cart>(cart));
}

/**
* 新增购物车
* 根据userId和itemId查询数据库
* 有数据: 数量的更新
* 无数据: 新增入库
*/
@Override
public void insertCart(Cart cart) {
QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>();
queryWrapper.eq("user_id", cart.getUserId())
.eq("item_id", cart.getItemId());
Cart cartDB = cartMapper.selectOne(queryWrapper);
if(cartDB == null) {
cart.setCreated(new Date())
.setUpdated(cart.getCreated());
cartMapper.insert(cart);
}else {
//数量更新      update tb_cart set num=#{num},updated = #{updated}  where id=#{id}
int num = cart.getNum() + cartDB.getNum();
Cart cartTemp = new Cart();
cartTemp.setId(cartDB.getId())
.setNum(num)
.setUpdated(new Date());
cartMapper.updateById(cartTemp);
}
}

 

posted @ 2020-03-02 10:33  唯恐不及  阅读(166)  评论(0编辑  收藏  举报