9.购物车
1.数据库
1.1 创建数据库
#1.使用use命令选中store数据库 use `store` #2.在store数据库中创建t_cart数据表 CREATE TABLE t_cart ( cid INT AUTO_INCREMENT COMMENT '购物车数据id', uid INT NOT NULL COMMENT '用户id', pid INT NOT NULL COMMENT '商品id', price BIGINT COMMENT '加入时商品单价', num INT COMMENT '商品数量', created_user VARCHAR(20) COMMENT '创建人', created_time DATETIME COMMENT '创建时间', modified_user VARCHAR(20) COMMENT '修改人', modified_time DATETIME COMMENT '修改时间', PRIMARY KEY (cid) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1.2 使用SQL执行现有数据表
1.3 执行结果
2.实体类
@Data public class Cart extends BaseEntity{ private Integer cid; private Integer uid; private Integer pid; private Long price; private Integer num; }
3.mapper层
3.1 添加购物车
3.1.1 mapper接口
/** * 插入购物车数据 * @param cart 购物车数据 * @return 受影响行数 */ Integer insert(Cart cart); /** * 根据购物车id修改商品数量 * @param cid * @return */ Integer updateNumByCid(@Param("cid") Integer cid, @Param("num") Integer num, @Param("modifiedUser") String modifiedUser, @Param("modifiedTime") Date modifiedTime); /** * 根据uid和pid查询购物车中数据 * @param uid 用户id * @param pid 商品id * @return 匹配的购物车数据,如果没有则为空 */ Cart findByUidAndPid(@Param("uid") Integer uid, @Param("pid") Integer pid);
3.1.2 CartMapper.xml
<resultMap id="cartEntityMap" type="com.ku.store.entity.Cart"> <id column="cid" property="cid"/> <result column="created_user" property="createdUser"/> <result column="created_time" property="createdTime"/> <result column="modified_user" property="modifiedUser"/> <result column="modified_time" property="modifiedTime"/> </resultMap> <insert id="insert" useGeneratedKeys="true" keyProperty="cid"> insert into store.t_cart(uid, pid, price, num, created_user, created_time, modified_user, modified_time) VALUES (#{uid}, #{pid}, #{price}, #{num}, #{createdUser}, #{createdTime}, #{modifiedUser}, #{modifiedTime}) </insert> <update id="updateNumByCid"> update store.t_cart set num = #{num}, modified_user = #{modifiedUser}, modified_time = #{modifiedTime} where cid = #{cid} </update> <select id="findByUidAndPid" resultMap="cartEntityMap"> select * from store.t_cart where uid = #{uid} and pid = #{pid} </select>
3.1.3 mapper测试
@Autowired CartMapper cartMapper; @Test public void insert(){ Cart cart = new Cart(); cart.setUid(1); cart.setPid(10000001); cart.setNum(100); cart.setPrice(6900L); Integer rows = cartMapper.insert(cart); System.out.println("rows:"+rows); } @Test public void updateNumByCid(){ Integer cid = 1; Integer num = 1000; String modifiedUser = "购物车管理员"; Integer rows = cartMapper.updateNumByCid(cid, num, modifiedUser, new Date()); System.out.println("rows:"+rows); } @Test public void findNumByUidAndPid(){ Integer uid = 1; Integer pid = 1000001; Cart result = cartMapper.findByUidAndPid(uid, pid); System.out.println("num:"+result); }
3.1.4 测试结果
3.2 显示购物车列表
3.2.1 VO类
显示购物车列表,需要关联商品类,无法在实体类中封装查询的数据,在这里使用VO类来展示controller层需要的数据
@Data public class CartVO implements Serializable { private Integer cid; private Integer uid; private Integer pid; private Long price; private Integer num; private String title; private Long realPrice; private String image; }
3.2.2 mapper接口
/** * 根据uid查询某用户的购物车数据 * @param uid * @return 该用户的购物车数据 */ List<CartVO> findVOByUid(Integer uid);
3.2.3 CartMapper.xml
<select id="findVOByUid" resultType="com.ku.store.vo.CartVO"> select cid, uid, pid, tc.price, tp.title, tp.price as realPrice, tp.image from store.t_cart as tc left join store.t_product as tp on tc.pid = tp.id where uid = #{uid} order by tc.created_time desc </select>
3.2.4 CartMapperTest
@Test public void findVOByUid(){ Integer uid = 9; List<CartVO> vos = cartMapper.findVOByUid(uid); System.out.println("vos:"+vos); }
3.2.5 测试结果
3.3增加商品数量
3.3.1 mapper接口
/** * 根据cid获取购物车数据 * @param cid 购物车id * @return 购物车数据 */ Cart findByCid(Integer cid);
3.3.2 CartMapper.xml
<select id="findByCid" resultMap="cartEntityMap"> select * from store.t_cart where cid = #{cid} </select>
3.3.3CartMapperTest
@Test public void findByCid(){ Integer cid = 1; Cart cart = cartMapper.findByCid(cid); System.out.println("cart:"+ cart); }
3.3.4 测试结果
3.4 显示勾选购物车数据
3.3.1mapper接口
/** * 通过若干个购物车id来显示勾选的商品列表 * @param cids 若干个购物车数据id * @return 匹配的购物车详情数据列表 */ List<CartVO> findVOByCids(Integer[] cids);
3.3.2 CartMapper.xml
<select id="findVOByCids" resultType="com.ku.store.vo.CartVO"> select cid, uid, pid, tc.price, tc.num, tp.title, tp.price as realPrice, tp.image from store.t_cart as tc left join store.t_product as tp on tc.pid = tp.id where cid in ( <foreach collection="array" item="cid" separator=","> #{cid} </foreach> ) order by tc.created_time desc </select>
3.3.3 CartMapperTest
@Test public void findVOByCids(){ Integer[] cids = {2,3}; List<CartVO> list = cartMapper.findVOByCids(cids); for (CartVO vo : list) { System.out.println(vo); } }
3.3.4 测试结果
4.service层
4.1 添加购物车
4.1.1 service接口
/** * 将商品添加到购物车中 * @param uid 用户id * @param pid 商品id * @param amount 增加的数量 * @param username 当前登录用户 */ void addToCart(Integer uid, Integer pid, Integer amount, String username);
4.1.2 CartServiceImpl
@Autowired CartMapper cartMapper; @Autowired IProductService productService; @Override public void addToCart(Integer uid, Integer pid, Integer amount, String username) { Cart result = cartMapper.findByUidAndPid(uid, pid); //当该购物车中没有该商品时 if(result == null){ System.out.println("用户未添加该商品!"); Cart cart = new Cart(); cart.setUid(uid); cart.setPid(pid); cart.setNum(amount); Product product = productService.getById(pid); cart.setPrice(product.getPrice()); cart.setCreatedUser(username); cart.setCreatedTime(new Date()); cart.setModifiedUser(username); cart.setModifiedTime(new Date()); Integer rows = cartMapper.insert(cart); if (rows != 1){ throw new InsertException("添加商品异常!"); } } //当购物车中有该商品时 Integer cid = result.getCid(); Integer num = result.getNum() + amount; Integer rows = cartMapper.updateNumByCid(cid, num, username, new Date()); if (rows != 1){ throw new UpdateException("修改商品数量出现异常!"); } }
4.1.3 service测试
@Autowired private ICartService cartService; @Test public void addToCart(){ try{ Integer uid = 1; Integer pid = 10000001; Integer num = 100; String username = "ku"; cartService.addToCart(uid, pid, num, username); System.out.println("修改成功!"); }catch( ServiceException e){ System.out.println(e.getClass().getSimpleName()); System.out.println(e.getMessage()); } }
4.1.4 测试结果
4.2 显示购物车列表
4.2.1 service接口
/** * 获取用户购物车列表 * @param uid 用户id * @return 用户购物车所有商品信息 */ List<CartVO> getVOByUid(Integer uid);
4.2.2 CartServiceImpl
@Override public List<CartVO> getVOByUid(Integer uid) { return cartMapper.findVOByUid(uid); }
4.2.3 service测试
@Test public void getVOByUid(){ try{ Integer uid = 1; List<CartVO> vos = cartService.getVOByUid(uid); for (CartVO vo : vos) { System.out.println(vo); } }catch( ServiceException e){ System.out.println(e.getClass().getSimpleName()); System.out.println(e.getMessage()); } }
4.2.4 测试结果
4.3 增加商品数量
4.3.1 service接口
/** * 将购物车中某商品数量加1 * @param cid 购物车id * @param uid 当前登录用户id * @param username 当前登录用户民 * @return 增加成功后数量 */ Integer addNum(Integer cid, Integer uid, String username);
4.3.2 CartServiceImpl
@Override public Integer addNum(Integer cid, Integer uid, String username) { //调用findByCid()根据参数cid查询购物车数据 Cart result = cartMapper.findByCid(cid); if(result == null){ throw new CartNotFoundException("购物车信息没找到!"); } //判断查询结果中的uid与参数uid是否一致 if(!result.getUid().equals(uid)){ throw new AccessDeniedException("非法登录!"); } //可选:检查商品的数量是否大于多少(适用于增加数量),或小于多少(适用于减少数量) Integer num = result.getNum() + 1; //Integer num = result,getNum() - 1; Integer rows = cartMapper.updateNumByCid(cid, num, username, new Date()); if(rows != 1){ throw new UpdateException("修改商品数量异常!"); } return num; }
4.3.3 service测试
@Test public void addNum(){ try{ Integer cid = 1; Integer uid = 1; String modifiedUser = "购物车管理员"; Integer num = cartService.addNum(cid, uid, modifiedUser); System.out.println("num:"+num); System.out.println("修改成功!"); }catch( ServiceException e){ System.out.println(e.getClass().getSimpleName()); System.out.println(e.getMessage()); } }
4.3.4 测试结果
4.4 显示勾选的购物车数据
4.3.1 service接口
/** * 根据uid 和若干个购物车id获取勾选商品详情 * @param uid 当前登录用户id * @param cids 若干个购物车id * @return 购物车数据详情列表 */ List<CartVO> getVOByCids(Integer uid, Integer[] cids);
4.3.2 CartServiceImpl
@Override public List<CartVO> getVOByCids(Integer uid, Integer[] cids) { List<CartVO> list = cartMapper.findVOByCids(cids); Iterator<CartVO> it = list.iterator();//删除和获取集合中的元素 while(it.hasNext()){ CartVO cart = it.next(); if (!cart.getUid().equals(uid)){ it.remove();//如果非法登录,移除购物车 } } return list; }
4.3.3 service测试
@Test public void getVOByCids(){ try{ Integer[] cids = {2, 3}; Integer uid = 9; List<CartVO> list = cartService.getVOByCids(uid, cids); for (CartVO cart : list) { System.out.println(cart); } }catch( ServiceException e){ System.out.println(e.getClass().getSimpleName()); System.out.println(e.getMessage()); } }
4.3.4 测试结果
5.controller层
5.1 添加购物车
5.1.1 BaseController
5.1.2 CartController
@Autowired private ICartService cartService; @RequestMapping("add_to_cart") public JsonResult<Void> addToCart(Integer pid, Integer amount, HttpSession session){
//从session中获取uid和username Integer uid = getUidFromSession(session); String username = getUsernameFromSession(session); cartService.addToCart(uid, pid, amount, username); return new JsonResult<Void>(OK); }
5.1.3 测试结果
先进行用户登录再访问http://localhost:8080/carts/add_to_cart?pid=1000001&amount=3
5.2 显示购物车列表
5.1.1 BaseController
5.1.2 CartController
@GetMapping({"","/"}) public JsonResult<List<CartVO>> getVOByUid(HttpSession session){ Integer uid = getUidFromSession(session); List<CartVO> data = cartService.getVOByUid(uid); return new JsonResult<List<CartVO>>(OK, data); }
5.1.3 测试结果
5.3 增加商品数量
5.1.1 BaseController
else if (e instanceof CartNotFoundException) { result.setState(407); result.setMessage("购物车数据找不到!"); }
5.1.2 CartController
@PostMapping("{cid}/num/add") public JsonResult<Integer> addNum(@PathVariable("cid") Integer cid, HttpSession session){ Integer uid = getUidFromSession(session); String username = getUsernameFromSession(session); Integer data = cartService.addNum(cid, uid, username); return new JsonResult<Integer>(OK, data); }
5.1.3 测试结果
5.4 显示勾选购物车数据
5.4.1 BaseController
5.4.2 UserController
@GetMapping("list") public JsonResult<List<CartVO>> getVOByCids(Integer[] cids, HttpSession session){ Integer uid = getUidFromSession(session); List<CartVO> data = cartService.getVOByCids(uid, cids); return new JsonResult<List<CartVO>>(OK, data); }
5.4.3 测试结果
6.小结
6.1 mapper层作用
主要是定义接口方法配合编写SQL语句为service层提供增删改查
6.2 service层作用
主要是实现具体的业务:注册、登录、修改信息等等,这离不开增删改查
6.3 controller层作用
主要是响应后端数据呈现给前端,由service具体业务连接到前端框架
7.反思
7.1 显示购物车列表
8.复盘
8.1 显示购物车列表