最新公告
  • 新注册用户请前往个人中心绑定邮箱以便接收相关凭证邮件!!!点击前往个人中心
  • 从零到企业级SSM电商项目实战教程(四十)创建订单,清空购物车等功能开发

    前台功能介绍

    1、创建订单

    2、商品信息

    3、订单列表

    4、订单详情

    5、取消订单

    后台功能介绍

    1、订单列表

    2、订单搜索

    3、订单详情

    4、订单发货

    学习目标

    1、避免业务逻辑中横向越权和纵向越权等安全漏洞

    2、设计实用、安全、扩展性强大的常量、枚举类

    3、订单号生成规则、订单严谨性判断

    4、PJO和VO之间的实际操练

    5、Mybatis批量插入

    OrderController.java

    @RequestMapping("create.do")
    @ResponseBody
    public ServerResponse create(HttpSession session, Integer shippingId) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
    
        return iOrderService.createOrder(user.getId(), shippingId);
    }
    

    IOrderService.java

    ServerResponse createOrder(Integer userId, Integer shippingId);
    

    OrderServiceImpl.java

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ShippingMapper shippingMapper;
    
    public ServerResponse createOrder(Integer userId, Integer shippingId) {
        //从购物车中获取数据
        List cartList = cartMapper.selectCheckedCartByUserId(userId);
        //计算这个订单的总价
        ServerResponse serverResponse = this.getCartOrderItem(userId, cartList);
        if (!serverResponse.isSuccess()) {
            return serverResponse;
        }
        List orderItemList = (List) serverResponse.getData();
        BigDecimal payment = this.getOrderTotalPrice(orderItemList);
        //生成订单
        Order order = this.assembleOrder(userId, shippingId, payment);
        if (order == null) {
            return ServerResponse.createByErrorMessage("生成订单错误");
        }
        if (CollectionUtils.isEmpty(orderItemList)) {
            return ServerResponse.createByErrorMessage("购物车为空");
        }
    
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderNo(order.getOrderNo());
        }
    
        //mybatis批量插入
        orderItemMapper.batchInsert(orderItemList);
        //生成成功,减少库存
        this.reduceProductStock(orderItemList);
        //清空购物车
        this.cleanCart(cartList);
    
        //返回给前端数据
        OrderVo orderVo = assembleOrderVo(order, orderItemList);
        return ServerResponse.createBySuccess(orderVo);
    }
    
    private OrderVo assembleOrderVo(Order order, List orderItemList) {
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(order.getOrderNo());
        orderVo.setPayment(order.getPayment());
        orderVo.setPaymentType(order.getPaymentType());
        orderVo.setPaymentTypeDesc(Const.PaymentTypeEnum.codeOf(order.getPaymentType()).getValue());
    
        orderVo.setPostage(order.getPostage());
        orderVo.setStatus(order.getStatus());
        orderVo.setStatusDesc(Const.OrderStatusEnum.codeOf(order.getStatus()).getValue());
    
        orderVo.setShippingId(order.getShippingId());
        Shipping shipping = shippingMapper.selectByPrimaryKey(order.getShippingId());
        if (shipping != null) {
            orderVo.setReceiverName(shipping.getReceiverName());
            orderVo.setShippingVo(assembleShippingVo(shipping));
        }
        orderVo.setPaymentTime(DateTimeUtil.dateToStr(order.getPaymentTime()));
        orderVo.setSendTime(DateTimeUtil.dateToStr(order.getSendTime()));
        orderVo.setEndTime(DateTimeUtil.dateToStr(order.getEndTime()));
        orderVo.setCreateTime(DateTimeUtil.dateToStr(order.getCreateTime()));
        orderVo.setCloseTime(DateTimeUtil.dateToStr(order.getCloseTime()));
    
        orderVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
    
        List orderItemVoList = Lists.newArrayList();
        for (OrderItem orderItem : orderItemList) {
            OrderItemVo orderItemVo = assembleOrderItemVo(orderItem);
            orderItemVoList.add(orderItemVo);
        }
        orderVo.setOrderItemVoList(orderItemVoList);
        return orderVo;
    }
    
    private OrderItemVo assembleOrderItemVo(OrderItem orderItem) {
        OrderItemVo orderItemVo = new OrderItemVo();
        orderItemVo.setOrderNo(orderItem.getOrderNo());
        orderItemVo.setProductId(orderItem.getProductId());
        orderItemVo.setProductName(orderItem.getProductName());
        orderItemVo.setProductImage(orderItem.getProductImage());
        orderItemVo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
        orderItemVo.setQuantity(orderItem.getQuantity());
        orderItemVo.setTotalPrice(orderItem.getTotalPrice());
    
        orderItemVo.setCreateTime(DateTimeUtil.dateToStr(orderItem.getCreateTime()));
        return orderItemVo;
    }
    
    private ShippingVo assembleShippingVo(Shipping shipping) {
        ShippingVo shippingVo = new ShippingVo();
        shippingVo.setReceiverName(shipping.getReceiverName());
        shippingVo.setReceiverAddress(shipping.getReceiverAddress());
        shippingVo.setReceiverProvince(shipping.getReceiverProvince());
        shippingVo.setReceiverCity(shipping.getReceiverCity());
        shippingVo.setReceiverDistrict(shipping.getReceiverDistrict());
        shippingVo.setReceiverMobile(shipping.getReceiverMobile());
        shippingVo.setReceiverZip(shipping.getReceiverZip());
        shippingVo.setReceiverPhone(shippingVo.getReceiverPhone());
        return shippingVo;
    }
    
    private void cleanCart(List cartList) {
        for (Cart cart : cartList) {
            cartMapper.deleteByPrimaryKey(cart.getId());
        }
    }
    
    private void reduceProductStock(List orderItemList) {
        for (OrderItem orderItem : orderItemList) {
            Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            product.setStock(product.getStock() - orderItem.getQuantity());
            productMapper.updateByPrimaryKeySelective(product);
        }
    }
    
    private Order assembleOrder(Integer userId, Integer shippingId, BigDecimal payment) {
        Order order = new Order();
        Long orderNo = this.generateOrderNo();
        order.setOrderNo(orderNo);
        order.setStatus(Const.OrderStatusEnum.NO_PAY.getCode());
        order.setPostage(0);
        order.setPaymentType(Const.PaymentTypeEnum.ONLINE_PAY.getCode());
        order.setPayment(payment);
        order.setUserId(userId);
        order.setShippingId(shippingId);
        //todo 各种时间
        int rowCount = orderMapper.insert(order);
        if (rowCount > 0) {
            return order;
        }
        return null;
    }
    
    private Long generateOrderNo() {
        Long currentTime = System.currentTimeMillis();
        //100个人并发,下单,不会失败。数据库中是唯一索引。
        return currentTime + new Random().nextInt(100);
    }
    
    private BigDecimal getOrderTotalPrice(List orderItemList) {
        BigDecimal payment = new BigDecimal("0");
        for (OrderItem orderItem : orderItemList) {
            payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
        }
        return payment;
    }
    
    private ServerResponse getCartOrderItem(Integer userId, List cartList) {
        List orderItemList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(cartList)) {
            return ServerResponse.createByErrorMessage("购物车为空");
        }
        //校验购物车的数据,包括产品的状态和数量
        for (Cart cartItem : cartList) {
            OrderItem orderItem = new OrderItem();
            Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
            if (Const.ProductStatusEnum.ON_SALE.getCode() != product.getStatus()) {
                return ServerResponse.createByErrorMessage("产品" + product.getName() + "不是在售商品");
            }
            //校验库存
            if (cartItem.getQuantity() > product.getStock()) {
                return ServerResponse.createByErrorMessage("产品" + product.getName() + "库存不足");
            }
            orderItem.setUserId(userId);
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentUnitPrice(product.getPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartItem.getQuantity()));
            orderItemList.add(orderItem);
        }
        return ServerResponse.createBySuccess(orderItemList);
    }
    

    CartMapper.java

    List selectCheckedCartByUserId(Integer userId);
    

    CartMapper.xml

    
    

    OrderItemMapper.java

    void batchInsert(@Param("orderItemList") List orderItemList);
    

    OrderItemMapper.xml

    
      insert into mmall_order_item (id, order_no,user_id, product_id,
      product_name, product_image, current_unit_price,
      quantity, total_price, create_time,
      update_time)
      values
      
        (
        #{item.id},#{item.orderNo},#{item.userId},#{item.productId},#{item.productName},#{item.productImage},#{item.currentUnitPrice},#{item.quantity},#{item.totalPrice},now(),now()
        )
      
    
    

    OrderVo.java

    package com.mmall.vo;
    
    import java.math.BigDecimal;
    import java.util.List;
    
    /**
     * @Author: Geekerstar(geekerstar.com)
     * @Date: 2018/6/25 12:20
     * @Description:
     */
    public class OrderVo {
        private Long orderNo;
        private BigDecimal payment;
        private Integer paymentType;
        private String paymentTypeDesc;
        private Integer postage;
    
        private Integer status;
        private String statusDesc;
        private String paymentTime;
    
        private String sendTime;
    
        private String endTime;
    
        private String closeTime;
    
        private String createTime;
    
        //订单明细
        private List orderItemVoList;
    
        private String imageHost;
        private Integer shippingId;
        private String receiverName;
    
        private ShippingVo shippingVo;
    
        public Long getOrderNo() {
            return orderNo;
        }
    
        public void setOrderNo(Long orderNo) {
            this.orderNo = orderNo;
        }
    
        public BigDecimal getPayment() {
            return payment;
        }
    
        public void setPayment(BigDecimal payment) {
            this.payment = payment;
        }
    
        public Integer getPaymentType() {
            return paymentType;
        }
    
        public void setPaymentType(Integer paymentType) {
            this.paymentType = paymentType;
        }
    
        public String getPaymentTypeDesc() {
            return paymentTypeDesc;
        }
    
        public void setPaymentTypeDesc(String paymentTypeDesc) {
            this.paymentTypeDesc = paymentTypeDesc;
        }
    
        public Integer getPostage() {
            return postage;
        }
    
        public void setPostage(Integer postage) {
            this.postage = postage;
        }
    
        public Integer getStatus() {
            return status;
        }
    
        public void setStatus(Integer status) {
            this.status = status;
        }
    
        public String getStatusDesc() {
            return statusDesc;
        }
    
        public void setStatusDesc(String statusDesc) {
            this.statusDesc = statusDesc;
        }
    
        public String getPaymentTime() {
            return paymentTime;
        }
    
        public void setPaymentTime(String paymentTime) {
            this.paymentTime = paymentTime;
        }
    
        public String getSendTime() {
            return sendTime;
        }
    
        public void setSendTime(String sendTime) {
            this.sendTime = sendTime;
        }
    
        public String getEndTime() {
            return endTime;
        }
    
        public void setEndTime(String endTime) {
            this.endTime = endTime;
        }
    
        public String getCloseTime() {
            return closeTime;
        }
    
        public void setCloseTime(String closeTime) {
            this.closeTime = closeTime;
        }
    
        public String getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(String createTime) {
            this.createTime = createTime;
        }
    
        public List getOrderItemVoList() {
            return orderItemVoList;
        }
    
        public void setOrderItemVoList(List orderItemVoList) {
            this.orderItemVoList = orderItemVoList;
        }
    
        public String getImageHost() {
            return imageHost;
        }
    
        public void setImageHost(String imageHost) {
            this.imageHost = imageHost;
        }
    
        public Integer getShippingId() {
            return shippingId;
        }
    
        public void setShippingId(Integer shippingId) {
            this.shippingId = shippingId;
        }
    
        public String getReceiverName() {
            return receiverName;
        }
    
        public void setReceiverName(String receiverName) {
            this.receiverName = receiverName;
        }
    
        public ShippingVo getShippingVo() {
            return shippingVo;
        }
    
        public void setShippingVo(ShippingVo shippingVo) {
            this.shippingVo = shippingVo;
        }
    }
    

    OrderItemVo.java

    package com.mmall.vo;
    
    import java.math.BigDecimal;
    
    /**
     * @Author: Geekerstar(geekerstar.com)
     * @Date: 2018/6/25 12:21
     * @Description:
     */
    public class OrderItemVo {
        private Long orderNo;
    
        private Integer productId;
    
        private String productName;
    
        private String productImage;
    
        private BigDecimal currentUnitPrice;
    
        private Integer quantity;
    
        private BigDecimal totalPrice;
    
        private String createTime;
    
        public Long getOrderNo() {
            return orderNo;
        }
    
        public void setOrderNo(Long orderNo) {
            this.orderNo = orderNo;
        }
    
        public Integer getProductId() {
            return productId;
        }
    
        public void setProductId(Integer productId) {
            this.productId = productId;
        }
    
        public String getProductName() {
            return productName;
        }
    
        public void setProductName(String productName) {
            this.productName = productName;
        }
    
        public String getProductImage() {
            return productImage;
        }
    
        public void setProductImage(String productImage) {
            this.productImage = productImage;
        }
    
        public BigDecimal getCurrentUnitPrice() {
            return currentUnitPrice;
        }
    
        public void setCurrentUnitPrice(BigDecimal currentUnitPrice) {
            this.currentUnitPrice = currentUnitPrice;
        }
    
        public Integer getQuantity() {
            return quantity;
        }
    
        public void setQuantity(Integer quantity) {
            this.quantity = quantity;
        }
    
        public BigDecimal getTotalPrice() {
            return totalPrice;
        }
    
        public void setTotalPrice(BigDecimal totalPrice) {
            this.totalPrice = totalPrice;
        }
    
        public String getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(String createTime) {
            this.createTime = createTime;
        }
    }
    

    ShippingVo.java

    package com.mmall.vo;
    
    /**
     * @Author: Geekerstar(geekerstar.com)
     * @Date: 2018/6/25 12:23
     * @Description:
     */
    public class ShippingVo {
        private String receiverName;
    
        private String receiverPhone;
    
        private String receiverMobile;
    
        private String receiverProvince;
    
        private String receiverCity;
    
        private String receiverDistrict;
    
        private String receiverAddress;
    
        private String receiverZip;
    
        public String getReceiverName() {
            return receiverName;
        }
    
        public void setReceiverName(String receiverName) {
            this.receiverName = receiverName;
        }
    
        public String getReceiverPhone() {
            return receiverPhone;
        }
    
        public void setReceiverPhone(String receiverPhone) {
            this.receiverPhone = receiverPhone;
        }
    
        public String getReceiverMobile() {
            return receiverMobile;
        }
    
        public void setReceiverMobile(String receiverMobile) {
            this.receiverMobile = receiverMobile;
        }
    
        public String getReceiverProvince() {
            return receiverProvince;
        }
    
        public void setReceiverProvince(String receiverProvince) {
            this.receiverProvince = receiverProvince;
        }
    
        public String getReceiverCity() {
            return receiverCity;
        }
    
        public void setReceiverCity(String receiverCity) {
            this.receiverCity = receiverCity;
        }
    
        public String getReceiverDistrict() {
            return receiverDistrict;
        }
    
        public void setReceiverDistrict(String receiverDistrict) {
            this.receiverDistrict = receiverDistrict;
        }
    
        public String getReceiverAddress() {
            return receiverAddress;
        }
    
        public void setReceiverAddress(String receiverAddress) {
            this.receiverAddress = receiverAddress;
        }
    
        public String getReceiverZip() {
            return receiverZip;
        }
    
        public void setReceiverZip(String receiverZip) {
            this.receiverZip = receiverZip;
        }
    }
    
    本站所有文章均由网友分享,仅用于参考学习用,请勿直接转载,如有侵权,请联系网站客服删除相关文章。若由于商用引起版权纠纷,一切责任均由使用者承担
    极客文库 » 从零到企业级SSM电商项目实战教程(四十)创建订单,清空购物车等功能开发

    常见问题FAQ

    如果资源链接失效了怎么办?
    本站用户分享的所有资源都有自动备份机制,如果资源链接失效,请联系本站客服QQ:2580505920更新资源地址。
    如果用户分享的资源与描述不符怎么办?
    可以联系客服QQ:2580505920,如果要求合理可以安排退款或者退赞助积分。
    如何分享个人资源获取赞助积分或其他奖励?
    本站用户可以分享自己的资源,但是必须保证资源没有侵权行为。点击个人中心,根据操作填写并上传即可。资源所获收益完全归属上传者,每周可申请提现一次。
    如果您发现了本资源有侵权行为怎么办?
    及时联系客服QQ:2580505920,核实予以删除。

    参与讨论

    • 211会员总数(位)
    • 3737资源总数(个)
    • 0本周发布(个)
    • 0 今日发布(个)
    • 919稳定运行(天)

    欢迎加入「极客文库」,成为原创作者从这里开始!

    立即加入 了解更多
    成为赞助用户享有更多特权立即升级