Exemple #1
0
  public void addItemToCart(Long itemId) {

    // 判断该商品是否存在购物车中
    // 如果存在,数量相加
    // 如果不存在,直接保存到数据库
    Cart record = new Cart();
    record.setItemId(itemId);
    record.setUserId(UserThreadLocal.get().getId());
    Cart cart = this.cartDao.selectOne(record);
    if (null == cart) {
      Item item = this.itemService.queryItemById(itemId);
      cart = new Cart();
      cart.setId(null);
      cart.setItemId(itemId);
      cart.setNum(1); // TODO 默认为1
      cart.setCreated(new Date());
      cart.setUpdated(cart.getCreated());
      cart.setUserId(record.getUserId());

      // 设置商品的基本数据
      cart.setItemTitle(item.getTitle());
      cart.setItemPrice(item.getPrice());
      String itemImage = item.getImage();
      if (StringUtils.isNotEmpty(itemImage)) {
        cart.setItemImage(StringUtils.split(itemImage, ",")[0]);
      }
      this.cartDao.insert(cart);
    } else {
      cart.setNum(cart.getNum() + 1); // TODO 先默认为1,项目实战中实现指定的购买数量
      cart.setUpdated(new Date());
      this.cartDao.updateByPrimaryKey(cart);
    }
  }
Exemple #2
0
 public List<Cart> queryCartList() {
   Long userId = UserThreadLocal.get().getId();
   Example example = new Example(Cart.class);
   example.setOrderByClause("created DESC");
   example.createCriteria().andEqualTo("userId", userId);
   List<Cart> cartList = cartDao.selectByExample(example);
   return cartList;
 }
Exemple #3
0
  public void updateItemNum(Long itemId, Integer num) {
    Example example = new Example(Cart.class);
    example.createCriteria().andEqualTo("userId", UserThreadLocal.get().getId());

    Cart cart = new Cart();
    cart.setItemId(itemId);
    cart.setNum(num);
    cartDao.updateByExample(cart, example);
  }
Exemple #4
0
 public void deleteItemFromCart(Long itemId) {
   Cart cart = new Cart();
   cart.setItemId(itemId);
   cart.setUserId(UserThreadLocal.get().getId());
   cartDao.delete(cart);
 }