package com.jt.cart.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jt.cart.service.CartService;
import com.jt.common.po.Cart;
import com.jt.common.vo.SysResult;
@Controller
@RequestMapping("/cart")
public class CartController {
@Autowired
private CartService cartService;
//根据用户id查询购物车信息
@RequestMapping("/query/{userId}")
@ResponseBody
public SysResult findCartByUserId(@PathVariable Long userId){
try {
List<Cart> cartList=cartService.findCartByUserId(userId);
return SysResult.oK(cartList);
} catch (Exception e) {
e.printStackTrace();
}
return SysResult.build(201, "购物车信息查询失败");
}
@RequestMapping("/save")
//实现购物车入库
public SysResult saveCart(Cart cart){
try {
cartService.saveCart(cart);
return SysResult.oK();
} catch (Exception e) {
// TODO: handle exception
}
return SysResult.build(201, "购物车新增失败");
}
}
package com.jt.cart.service;
import java.util.List;
import com.jt.common.po.Cart;
public interface CartService {
List<Cart> findCartByUserId(Long userId);
void saveCart(Cart cart);
}
package com.jt.cart.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jt.cart.mapper.CartMapper;
import com.jt.common.po.Cart;
@Service
public class CartServiceImpl implements CartService {
@Autowired
private CartMapper cartMapper;
@Override
public List<Cart> findCartByUserId(Long userId) {
Cart cart=new Cart();
cart.setUserId(userId);
return cartMapper.select(cart);
}
/**
* 根据userId和itemId判断数据库中是否有该购物车信息
* 有
* 数据库num+新num做更新操作
* 没有数据
* 应该插入数据库
*/
/* (non-Javadoc)
* @see com.jt.cart.service.CartService#saveCart(com.jt.common.po.Cart)
*/
@Override
public void saveCart(Cart cart) {
Cart cartDB=cartMapper.findCartByUI(cart);
if(cartDB==null){
System.out.println("insert cart");
cart.setCreated(new Date());
cart.setUpdated(cart.getCreated());
cartMapper.insert(cart);
}else{
System.out.println("insert cart2");
int num=cartDB.getNum()+cart.getNum();
cartDB.setNum(num);
cartDB.setUpdated(new Date());
cartMapper.updateByPrimaryKeySelective(cartDB);
}
}
}
package com.jt.cart.mapper;
import org.apache.ibatis.annotations.Select;
import com.jt.common.mapper.SysMapper;
import com.jt.common.po.Cart;
public interface CartMapper extends SysMapper<Cart>{
@Select("select * from tb_cart where item_id=#{itemId} and user_id=#{userId}")
Cart findCartByUI(Cart cart);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace="它是映射文件的唯一标识"-相当于配置文件的主键
mapper接口调用方式,表明mapper接口/映射文件/表映射关系,用接口的全路径名称 -->
<mapper namespace="com.jt.cart.mapper.CartMapper">
</mapper>