一、sql

/*
 Navicat Premium Data Transfer

 Source Server         : testOne
 Source Server Type    : MySQL
 Source Server Version : 80028
 Source Host           : localhost:3306
 Source Schema         : miaosha

 Target Server Type    : MySQL
 Target Server Version : 80028
 File Encoding         : 65001

 Date: 21/04/2022 19:08:34
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for promo
-- ----------------------------
DROP TABLE IF EXISTS `promo`;
CREATE TABLE `promo`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `promo_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `start_time` datetime(0) NOT NULL,
  `item_id` int(0) NOT NULL DEFAULT 0,
  `promo_item_price` decimal(10, 0) NOT NULL DEFAULT 0,
  `end_time` datetime(0) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of promo
-- ----------------------------
INSERT INTO `promo` VALUES (1, 'iphone4抢购', '2022-04-21 15:03:00', 4, 500, '2022-04-21 14:36:00');

SET FOREIGN_KEY_CHECKS = 1;
1 <!--promo表-->
2         <table tableName="promo" domainObjectName="PromoDO"
3                enableCountByExample="false" enableUpdateByExample="false"
4                enableDeleteByExample="false" enableSelectByExample="false"
5                selectByExampleQueryId="false" enableInsert="true"
6                enableDeleteByPrimaryKey="false"></table>
ALTER TABLE order_info ADD promo_id INT NOT NULL DEFAULT 0

 

二、Model

1.PromoModel

 1 package com.miaoshaProject.service.model;
 2 
 3 import org.joda.time.DateTime;
 4 
 5 import javax.xml.crypto.Data;
 6 import java.math.BigDecimal;
 7 
 8 /**
 9  * @Author wangshuo
10  * @Date 2022/4/21, 8:49
11  * 营销(秒杀模型)
12  */
13 public class PromoModel {
14 
15     private Integer id;
16 
17     private String promoName;
18 
19     private DateTime startTime;
20 
21     private DateTime endTime;
22 
23     private Integer itemId;
24 
25     //秒杀活动状态 1.还未开始 2.进行中 3.已结束
26     private Integer status;
27 
28     public Integer getStatus() {
29         return status;
30     }
31 
32     public void setStatus(Integer status) {
33         this.status = status;
34     }
35 
36     public DateTime getEndTime() {
37         return endTime;
38     }
39 
40     public void setEndTime(DateTime endTime) {
41         this.endTime = endTime;
42     }
43 
44     //秒杀活动的价格
45     private BigDecimal promoItemPrice;
46 
47     public Integer getId() {
48         return id;
49     }
50 
51     public void setId(Integer id) {
52         this.id = id;
53     }
54 
55     public String getPromoName() {
56         return promoName;
57     }
58 
59     public void setPromoName(String promoName) {
60         this.promoName = promoName;
61     }
62 
63     public DateTime getStartTime() {
64         return startTime;
65     }
66 
67     public void setStartTime(DateTime startTime) {
68         this.startTime = startTime;
69     }
70 
71     public Integer getItemId() {
72         return itemId;
73     }
74 
75     public void setItemId(Integer itemId) {
76         this.itemId = itemId;
77     }
78 
79     public BigDecimal getPromoItemPrice() {
80         return promoItemPrice;
81     }
82 
83     public void setPromoItemPrice(BigDecimal promoItemPrice) {
84         this.promoItemPrice = promoItemPrice;
85     }
86 }

2.OrderModel

 1 package com.miaoshaProject.service.model;
 2 
 3 import java.math.BigDecimal;
 4 
 5 /**
 6  * @Author wangshuo
 7  * @Date 2022/4/20, 8:45
 8  * 用户下单的交易模型
 9  */
10 public class OrderModel {
11 
12     //String类型id
13     private String id;
14 
15     private Integer userId;
16 
17     private Integer itemId;
18 
19     //若非空,表示该商品是秒杀商品
20     private Integer promoId;
21 
22     //商品数量 若promoId非空则表示秒杀商品价格
23     private Integer amount;
24 
25     //订单金额
26     private BigDecimal orderPrice;
27 
28     public Integer getPromoId() {
29         return promoId;
30     }
31 
32     public void setPromoId(Integer promoId) {
33         this.promoId = promoId;
34     }
35 
36     //冗余一个字段  若promoId非空则表示秒杀订单价格
37     private BigDecimal itemPrice;
38 
39     public String getId() {
40         return id;
41     }
42 
43     public void setId(String id) {
44         this.id = id;
45     }
46 
47     public Integer getUserId() {
48         return userId;
49     }
50 
51     public void setUserId(Integer userId) {
52         this.userId = userId;
53     }
54 
55     public Integer getItemId() {
56         return itemId;
57     }
58 
59     public void setItemId(Integer itemId) {
60         this.itemId = itemId;
61     }
62 
63     public Integer getAmount() {
64         return amount;
65     }
66 
67     public void setAmount(Integer amount) {
68         this.amount = amount;
69     }
70 
71     public BigDecimal getOrderPrice() {
72         return orderPrice;
73     }
74 
75     public void setOrderPrice(BigDecimal orderPrice) {
76         this.orderPrice = orderPrice;
77     }
78 
79     public BigDecimal getItemPrice() {
80         return itemPrice;
81     }
82 
83     public void setItemPrice(BigDecimal itemPrice) {
84         this.itemPrice = itemPrice;
85     }
86 }

3.ItemModel

  1 package com.miaoshaProject.service.model;
  2 
  3 import javax.validation.constraints.Min;
  4 import javax.validation.constraints.NotBlank;
  5 import javax.validation.constraints.NotNull;
  6 import java.io.Serializable;
  7 import java.math.BigDecimal;
  8 
  9 /**
 10  * @Author wangshuo
 11  * @Date 2022/4/18, 8:45
 12  * Please add a comment
 13  */
 14 public class ItemModel implements Serializable {
 15 
 16     private Integer id;
 17 
 18     @NotBlank(message = "商品名称不能为空")
 19     private String title;
 20 
 21     @NotNull(message = "商品价格不能为空")
 22     @Min(message = "商品价格必须大于零",value = 0)
 23     private BigDecimal price;
 24 
 25     @NotNull(message = "商品库存不能不填")
 26     private Integer stock;
 27 
 28     @NotBlank(message = "商品描述不能为空")
 29     private String description;
 30 
 31     private Integer sales;
 32 
 33     //商品描述图片的url
 34     @NotBlank(message = "图片信息不能为空")
 35     private String imgUrl;
 36 
 37     //使用聚合模型 如果promoModel不为空则表示其拥有还未结束的秒杀活动
 38     private PromoModel promoModel;
 39 
 40     public PromoModel getPromoModel() {
 41         return promoModel;
 42     }
 43 
 44     public void setPromoModel(PromoModel promoModel) {
 45         this.promoModel = promoModel;
 46     }
 47 
 48     public Integer getId() {
 49         return id;
 50     }
 51 
 52     public void setId(Integer id) {
 53         this.id = id;
 54     }
 55 
 56     public String getTitle() {
 57         return title;
 58     }
 59 
 60     public void setTitle(String title) {
 61         this.title = title;
 62     }
 63 
 64     public BigDecimal getPrice() {
 65         return price;
 66     }
 67 
 68     public void setPrice(BigDecimal price) {
 69         this.price = price;
 70     }
 71 
 72     public Integer getStock() {
 73         return stock;
 74     }
 75 
 76     public void setStock(Integer stock) {
 77         this.stock = stock;
 78     }
 79 
 80     public String getDescription() {
 81         return description;
 82     }
 83 
 84     public void setDescription(String description) {
 85         this.description = description;
 86     }
 87 
 88     public Integer getSales() {
 89         return sales;
 90     }
 91 
 92     public void setSales(Integer sales) {
 93         this.sales = sales;
 94     }
 95 
 96     public String getImgUrl() {
 97         return imgUrl;
 98     }
 99 
100     public void setImgUrl(String imgUrl) {
101         this.imgUrl = imgUrl;
102     }
103 }

4.ItemVO

  1 package com.miaoshaProject.controller.viewobject;
  2 
  3 import org.joda.time.DateTime;
  4 
  5 import java.math.BigDecimal;
  6 
  7 /**
  8  * @Author wangshuo
  9  * @Date 2022/4/19, 10:47
 10  * Please add a comment
 11  */
 12 public class ItemVO {
 13 
 14     private Integer id;
 15 
 16     private String title;
 17 
 18     private BigDecimal price;
 19 
 20     private String description;
 21 
 22     private Integer sales;
 23 
 24     private String imgUrl;
 25 
 26     private Integer stock;
 27 
 28     //记录商品是否在秒杀活动中,以及对应的状态 0.无活动 1.未开始 2.进行中 3.已结束
 29     private Integer promoStatus;
 30 
 31     private BigDecimal promoPrice;
 32 
 33     private Integer promoId;
 34 
 35     private String startTime;
 36 
 37     public Integer getPromoStatus() {
 38         return promoStatus;
 39     }
 40 
 41     public void setPromoStatus(Integer promoStatus) {
 42         this.promoStatus = promoStatus;
 43     }
 44 
 45     public BigDecimal getPromoPrice() {
 46         return promoPrice;
 47     }
 48 
 49     public void setPromoPrice(BigDecimal promoPrice) {
 50         this.promoPrice = promoPrice;
 51     }
 52 
 53     public Integer getPromoId() {
 54         return promoId;
 55     }
 56 
 57     public void setPromoId(Integer promoId) {
 58         this.promoId = promoId;
 59     }
 60 
 61     public String getStartTime() {
 62         return startTime;
 63     }
 64 
 65     public void setStartTime(String startTime) {
 66         this.startTime = startTime;
 67     }
 68 
 69     public Integer getId() {
 70         return id;
 71     }
 72 
 73     public void setId(Integer id) {
 74         this.id = id;
 75     }
 76 
 77     public String getTitle() {
 78         return title;
 79     }
 80 
 81     public void setTitle(String title) {
 82         this.title = title;
 83     }
 84 
 85     public BigDecimal getPrice() {
 86         return price;
 87     }
 88 
 89     public void setPrice(BigDecimal price) {
 90         this.price = price;
 91     }
 92 
 93     public String getDescription() {
 94         return description;
 95     }
 96 
 97     public void setDescription(String description) {
 98         this.description = description;
 99     }
100 
101     public Integer getSales() {
102         return sales;
103     }
104 
105     public void setSales(Integer sales) {
106         this.sales = sales;
107     }
108 
109     public String getImgUrl() {
110         return imgUrl;
111     }
112 
113     public void setImgUrl(String imgUrl) {
114         this.imgUrl = imgUrl;
115     }
116 
117     public Integer getStock() {
118         return stock;
119     }
120 
121     public void setStock(Integer stock) {
122         this.stock = stock;
123     }
124 }

 

三、活动信息

1.修改根据id查商品详情

 1 @Override
 2     public ItemModel getItemById(Integer id) {
 3 
 4         ItemDO itemDO = itemDOMapper.selectByPrimaryKey(id);
 5         if (itemDO == null)
 6             return null;
 7         //操作获得库存数量
 8         ItemStockDO itemStockDO = itemStockDOMapper.selectByItemId(id);
 9         //convert
10         ItemModel itemModel = convertModelFromDataObject(itemDO, itemStockDO);
11 
12         //获取活动商品信息
13         PromoModel promoModel = promoService.getPromoByItemId(itemModel.getId());
14         if (promoModel != null && promoModel.getStatus() != 3)
15             itemModel.setPromoModel(promoModel);
16         return itemModel;
17     }

2.getItem.html

<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="assets/global/plugins/bootstrap/css/bootstrap.min.css" type="text/css"/>
    <link rel="stylesheet" href="assets/global/css/components.css" type="text/css"/>
    <link rel="stylesheet" href="assets/admin/pages/css/login.css" type="text/css"/>
    <script rel="stylesheet" src="assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
</head>
<body class="login" background="edge_bj_1.jpg">

<div class="content">
    <h3 class="form-title">商品详情</h3>
    <div id="promoStartTimeContainer" class="form-group">
        <!--<label class="control-label" style="font-size: 18px;color: blue">秒杀开始时间</label>-->
        <div>
            <label style="color: red" class="control-label" id="promoStartTime"/>
        </div>
    </div>
    <div class="form-group">
        <div>
            <label class="control-label" id="title"/>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label" style="font-size: 18px">商品描述</label>
        <div>
            <label class="control-label" id="description"/>
        </div>
    </div>
    <div id="normalPriceContainer" class="form-group">
        <label  class="control-label" style="font-size: 18px">商品价格</label>
        <div>
            <label class="control-label" id="price"/>
        </div>
    </div>
    <div id="promoPriceContainer" class="form-group">
        <label class="control-label" style="font-size: 18px;color: red">秒杀价格</label>
        <div>
            <label style="color: red" class="control-label" id="promoPrice"/>
        </div>
    </div>
    <div class="form-group">
        <div>
            <img style="height: 200px;width: auto" id="imgUrl">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label" style="font-size: 18px">商品库存</label>
        <div>
            <label class="control-label" id="stock"/>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label" style="font-size: 18px">商品销量</label>
        <div>
            <label class="control-label" id="sales"/>
        </div>
    </div>
    <div class="from-actions">
        <button class="btn blue" id="createorder" type="submit">
            下单
        </button>
    </div>
</div>

</body>
<script>

    function getParam(paramName) {
        paramValue = "", isFound = !1;
        if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {
            arrSource = unescape(this.location.search).substring(1, this.location.search.length).split("&"), i = 0;
            while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
        }
        return paramValue == "" && (paramValue = null), paramValue
    }

    function reloadDom() {

        $("#title").text(g_itemVO.title);
        $("#description").text(g_itemVO.description);
        $("#stock").text(g_itemVO.stock);
        $("#price").text(g_itemVO.price);
        $("#sales").text(g_itemVO.sales);
        $("#imgUrl").attr("src", g_itemVO.imgUrl);
        if (g_itemVO.promoStatus == 1){
            //秒杀活动还未开始
            var time = g_itemVO.startTime;
            var startTime = time.replace(new RegExp("-","gm"),"/");
            startTime = (new Date(startTime)).getTime();
            var nowTime = Date.parse(new Date());
            var delta = (startTime - nowTime)/1000;

            //活动开始
            if (delta <= 0){

                g_itemVO.promoStatus = 2;
                reloadDom();
            }
            $("#promoStartTime").text("秒杀活动将于"+g_itemVO.startTime+"开始  倒计时:"+delta+"")
            $("#promoPrice").text(g_itemVO.promoPrice);
            $("#createorder").attr("disabled",true);
        }else if (g_itemVO.promoStatus == 2){

            //秒杀正在进行中
            $("#promoStartTime").text("秒杀活动进行中!")
            $("#promoPrice").text(g_itemVO.promoPrice);
            $("#createorder").attr("disabled",false);
            $("#normalPriceContainer").hide();
        }else {
            //没有秒杀活动或者秒杀已经结束
            $("#promoStartTimeContainer").attr("hidden",true)
            $("#promoPriceContainer").attr("hidden",true)
        }

    }

    var g_itemVO = {};

    jQuery(document).ready(function () {

        //下单
        $("#createorder").on("click", function () {
            $.ajax({
                type: "POST",
                contentType: "application/x-www-form-urlencoded",
                url: "http://localhost:8080/order/create",
                data: {
                    "itemId": g_itemVO.id,
                    "amount": 1,
                    "promoId": g_itemVO.promoId,
                },
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (result) {

                    if (result.status == "success") {
                        alert("购买成功")
                        //刷新界面
                        window.location.reload();
                    } else {
                        alert("请求失败 原因为:" + result.data.errMsg)
                    }
                },
                error: function (result) {
                    alert("请求失败  原因为" + result.responseText)
                }
            })
            return false;
        })

        //获取商品详情
        $.ajax({
            type: "GET",
            contentType: "application/x-www-form-urlencoded",
            url: "http://localhost:8080/item/get",
            data: {
                "id": getParam("id")
            },
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function (result) {

                if (result.status == "success") {
                    g_itemVO = result.data;
                    reloadDom();
                    //每隔一秒钟刷新一次页面
                    setInterval(reloadDom,1000)
                } else {
                    alert("请求失败 原因为:" + result.data.errMsg)
                }
            },
            error: function (result) {
                alert("请求失败  原因为" + result.responseText)
            }
        })
    })
</script>
</html>

四、秒杀

1.OrderController

 1 package com.miaoshaProject.controller;
 2 
 3 import com.miaoshaProject.error.BusinessException;
 4 import com.miaoshaProject.error.EnumBusinessError;
 5 import com.miaoshaProject.response.CommonReturnType;
 6 import com.miaoshaProject.service.OrderService;
 7 import com.miaoshaProject.service.model.OrderModel;
 8 import com.miaoshaProject.service.model.UserModel;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.stereotype.Controller;
11 import org.springframework.web.bind.annotation.CrossOrigin;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 import org.springframework.web.bind.annotation.RequestParam;
14 import org.springframework.web.bind.annotation.ResponseBody;
15 
16 import javax.servlet.http.Cookie;
17 import javax.servlet.http.HttpServletRequest;
18 import java.io.UnsupportedEncodingException;
19 import java.net.URLDecoder;
20 
21 /**
22  * @Author wangshuo
23  * @Date 2022/4/20, 14:17
24  * Please add a comment
25  */
26 @Controller("order")
27 @RequestMapping("/order")
28 @CrossOrigin(origins = {"*"}, allowCredentials = "true")
29 public class OrderController extends BaseController {
30 
31     @Autowired
32     OrderService orderService;
33 
34     //封装下单请求
35     @RequestMapping("/create")
36     @ResponseBody
37     public CommonReturnType create(@RequestParam(name = "itemId") Integer itemId,
38                                    @RequestParam(name = "amount") Integer amount,
39                                    @RequestParam(name = "promoId",required = false) Integer promoId,
40                                    HttpServletRequest request) throws BusinessException {
41 
42         //获取user信息
43         /*Integer login_id = (Integer) request.getSession().getAttribute("LOGIN_USER");*/
44         Cookie[] cookieList = request.getCookies();
45         if (cookieList == null) {
46             return null;
47         }
48         String retValue = null;
49         for (int i = 0; i < cookieList.length; i++) {
50             if (cookieList[i].getName().equals("LOGIN_USER")) {
51 
52                 retValue = cookieList[i].getValue();
53                 break;
54             }
55         }
56         OrderModel orderModel = new OrderModel();
57         if (retValue == null) {
58             /*throw new BusinessException(EnumBusinessError.USER_NOT_EXISTS,"用户未登录");*/
59             orderModel = orderService.createOrder(17, itemId, promoId, amount);
60         } else
61             orderModel = orderService.createOrder(Integer.parseInt(retValue), itemId, promoId, amount);
62         return CommonReturnType.create(orderModel);
63     }
64 }

2.OrderServiceImpl

  1 package com.miaoshaProject.service.impl;
  2 
  3 import com.miaoshaProject.dao.OrderDOMapper;
  4 import com.miaoshaProject.dao.SequenceDOMapper;
  5 import com.miaoshaProject.dataobject.OrderDO;
  6 import com.miaoshaProject.dataobject.SequenceDO;
  7 import com.miaoshaProject.error.BusinessException;
  8 import com.miaoshaProject.error.EnumBusinessError;
  9 import com.miaoshaProject.service.ItemService;
 10 import com.miaoshaProject.service.OrderService;
 11 import com.miaoshaProject.service.UesrService;
 12 import com.miaoshaProject.service.model.ItemModel;
 13 import com.miaoshaProject.service.model.OrderModel;
 14 import com.miaoshaProject.service.model.UserModel;
 15 import org.springframework.beans.BeanUtils;
 16 import org.springframework.beans.factory.annotation.Autowired;
 17 import org.springframework.stereotype.Service;
 18 import org.springframework.transaction.annotation.Propagation;
 19 import org.springframework.transaction.annotation.Transactional;
 20 
 21 import java.math.BigDecimal;
 22 import java.time.LocalDateTime;
 23 import java.time.format.DateTimeFormatter;
 24 import java.util.Date;
 25 
 26 /**
 27  * @Author wangshuo
 28  * @Date 2022/4/20, 9:35
 29  * Please add a comment
 30  */
 31 @Service
 32 public class OrderServiceImpl implements OrderService {
 33 
 34     @Autowired
 35     OrderDOMapper orderDOMapper;
 36 
 37     @Autowired
 38     ItemService itemService;
 39 
 40     @Autowired
 41     UesrService uesrService;
 42 
 43     @Autowired
 44     SequenceDOMapper sequenceDOMapper;
 45 
 46     @Override
 47     @Transactional
 48     public OrderModel createOrder(Integer userId, Integer itemId, Integer promoId, Integer amount) throws BusinessException {
 49 
 50         //校验下单状态 : 下单的商品是否存在,用户是否合法,购买数量是否正确
 51         ItemModel itemModel = itemService.getItemById(itemId);
 52         if (itemModel == null)
 53             throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, "商品信息不存在");
 54         //校验用户信息
 55         UserModel byId = uesrService.getById(userId);
 56         if (byId == null)
 57             throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, "用户信息不存在");
 58         //校验库存信息
 59         if (amount <= 0 || amount > 99)
 60             throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, "订单数量不正确");
 61         //校验活动信息
 62         if (promoId != null) {
 63             //是否有对应活动商品
 64             if (promoId.intValue() != itemModel.getPromoModel().getId())
 65                 throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, "活动信息出错");
 66             //活动是否正在进行中
 67             if (itemModel.getPromoModel().getStatus() != 2)
 68                 throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, "活动信息出错");
 69         }
 70         //落单减库存
 71         boolean b = itemService.decreaseStock(itemId, amount);
 72         if (!b)
 73             throw new BusinessException(EnumBusinessError.STOCK_NOT_ENOUGH);
 74         //订单入库
 75         OrderModel orderModel = new OrderModel();
 76         orderModel.setUserId(userId);
 77         orderModel.setItemId(itemId);
 78         orderModel.setPromoId(promoId);
 79         orderModel.setAmount(amount);
 80         if (promoId != null)
 81             orderModel.setItemPrice(itemModel.getPromoModel().getPromoItemPrice());
 82         else
 83             orderModel.setItemPrice(itemModel.getPrice());
 84         //相乘获得订单价格
 85         orderModel.setOrderPrice(orderModel.getItemPrice().multiply(new BigDecimal(amount)));
 86         //交易流水订单号
 87         orderModel.setId(generateOrderNO());
 88         //转化model
 89         OrderDO orderDO = convertFromOrderModel(orderModel);
 90         //新增订单
 91         orderDOMapper.insertSelective(orderDO);
 92         //增加销量
 93         itemService.increaseSales(orderModel);
 94         //返回前端
 95         return orderModel;
 96     }
 97 
 98     @Transactional(propagation = Propagation.REQUIRES_NEW)//不论外部事务成功与否 我这边都要提交事务,保证自增序列唯一性
 99     public String generateOrderNO() {
100         //设计 : 订单号有十六位,
101         StringBuilder stringBuilder = new StringBuilder();
102         // 前八位为时间信息
103         LocalDateTime date = LocalDateTime.now();
104         stringBuilder.append(date.format(DateTimeFormatter.ISO_DATE).replace("-", ""));
105         // 中间六位为自增序列
106         Integer sequence = 0;
107         //1.获取当前sequence
108         SequenceDO sequence_info = sequenceDOMapper.getSequenceByName("order_info");
109         sequence = sequence_info.getCurrentValue();
110         //2.sequence增加步长并入库
111         sequence_info.setCurrentValue(sequence_info.getCurrentValue() + sequence_info.getStep());
112         sequenceDOMapper.updateByPrimaryKeySelective(sequence_info);
113         //3.拼接sequence
114         String sequenceStr = String.valueOf(sequence);
115         for (int i = 0; i < 6 - sequenceStr.length(); i++) {//当sequence被操作六位数以上后,中间自增序列就不止六位数了
116             stringBuilder.append(0);
117         }
118         stringBuilder.append(sequenceStr);
119         // 最后两位为分库分表位   暂时写死为00
120         stringBuilder.append("00");
121         return stringBuilder.toString();
122     }
123 
124     private OrderDO convertFromOrderModel(OrderModel orderModel) {
125 
126         if (orderModel == null)
127             return null;
128         OrderDO orderDO = new OrderDO();
129         BeanUtils.copyProperties(orderModel, orderDO);
130         return orderDO;
131     }
132 }

五、mapper

1     <select id="selectByItemId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
2         select
3         <include refid="Base_Column_List"/>
4         from promo
5         where item_id = #{itemId,jdbcType=INTEGER}
6     </select>
<?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">
<mapper namespace="com.miaoshaProject.dao.OrderDOMapper">
    <resultMap id="BaseResultMap" type="com.miaoshaProject.dataobject.OrderDO">
        <!--
          WARNING - @mbg.generated
          This element is automatically generated by MyBatis Generator, do not modify.
          This element was generated on Wed Apr 20 09:19:18 CST 2022.
        -->
        <id column="id" jdbcType="VARCHAR" property="id"/>
        <result column="user_id" jdbcType="INTEGER" property="userId"/>
        <result column="item_id" jdbcType="INTEGER" property="itemId"/>
        <result column="item_price" jdbcType="DECIMAL" property="itemPrice"/>
        <result column="amount" jdbcType="INTEGER" property="amount"/>
        <result column="order_price" jdbcType="DECIMAL" property="orderPrice"/>
        <result column="promo_id" jdbcType="DECIMAL" property="promoId"/>
    </resultMap>
    <sql id="Base_Column_List">
        <!--
          WARNING - @mbg.generated
          This element is automatically generated by MyBatis Generator, do not modify.
          This element was generated on Wed Apr 20 09:19:18 CST 2022.
        -->
        id, user_id, item_id, item_price, amount, order_price,promoId
    </sql>
    <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
        <!--
          WARNING - @mbg.generated
          This element is automatically generated by MyBatis Generator, do not modify.
          This element was generated on Wed Apr 20 09:19:18 CST 2022.
        -->
        select
        <include refid="Base_Column_List"/>
        from order_info
        where id = #{id,jdbcType=VARCHAR}
    </select>
    <insert id="insert" parameterType="com.miaoshaProject.dataobject.OrderDO">
        <!--
          WARNING - @mbg.generated
          This element is automatically generated by MyBatis Generator, do not modify.
          This element was generated on Wed Apr 20 09:19:18 CST 2022.
        -->
        insert into order_info (id, user_id, item_id,
        item_price, amount, order_price,promo_id
        )
        values (#{id,jdbcType=VARCHAR}, #{userId,jdbcType=INTEGER}, #{itemId,jdbcType=INTEGER},
        #{itemPrice,jdbcType=DECIMAL}, #{amount,jdbcType=INTEGER}, #{orderPrice,jdbcType=DECIMAL}
        , #{promoId,jdbcType=DECIMAL}
        )
    </insert>
    <insert id="insertSelective" parameterType="com.miaoshaProject.dataobject.OrderDO">
        <!--
          WARNING - @mbg.generated
          This element is automatically generated by MyBatis Generator, do not modify.
          This element was generated on Wed Apr 20 09:19:18 CST 2022.
        -->
        insert into order_info
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="userId != null">
                user_id,
            </if>
            <if test="itemId != null">
                item_id,
            </if>
            <if test="itemPrice != null">
                item_price,
            </if>
            <if test="amount != null">
                amount,
            </if>
            <if test="orderPrice != null">
                order_price,
            </if>
            <if test="promoId != null">
                promo_id,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=VARCHAR},
            </if>
            <if test="userId != null">
                #{userId,jdbcType=INTEGER},
            </if>
            <if test="itemId != null">
                #{itemId,jdbcType=INTEGER},
            </if>
            <if test="itemPrice != null">
                #{itemPrice,jdbcType=DECIMAL},
            </if>
            <if test="amount != null">
                #{amount,jdbcType=INTEGER},
            </if>
            <if test="orderPrice != null">
                #{orderPrice,jdbcType=DECIMAL},
            </if>
            <if test="promoId != null">
                #{promoId,jdbcType=DECIMAL},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.miaoshaProject.dataobject.OrderDO">
        <!--
          WARNING - @mbg.generated
          This element is automatically generated by MyBatis Generator, do not modify.
          This element was generated on Wed Apr 20 09:19:18 CST 2022.
        -->
        update order_info
        <set>
            <if test="userId != null">
                user_id = #{userId,jdbcType=INTEGER},
            </if>
            <if test="itemId != null">
                item_id = #{itemId,jdbcType=INTEGER},
            </if>
            <if test="itemPrice != null">
                item_price = #{itemPrice,jdbcType=DECIMAL},
            </if>
            <if test="amount != null">
                amount = #{amount,jdbcType=INTEGER},
            </if>
            <if test="orderPrice != null">
                order_price = #{orderPrice,jdbcType=DECIMAL},
            </if>
            <if test="promoId != null">
                promo_id = #{promoId,jdbcType=DECIMAL},
            </if>
        </set>
        where id = #{id,jdbcType=VARCHAR}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.miaoshaProject.dataobject.OrderDO">
        <!--
          WARNING - @mbg.generated
          This element is automatically generated by MyBatis Generator, do not modify.
          This element was generated on Wed Apr 20 09:19:18 CST 2022.
        -->
        update order_info
        set user_id = #{userId,jdbcType=INTEGER},
        item_id = #{itemId,jdbcType=INTEGER},
        item_price = #{itemPrice,jdbcType=DECIMAL},
        amount = #{amount,jdbcType=INTEGER},
        order_price = #{orderPrice,jdbcType=DECIMAL},
        promo_id = #{promoId,jdbcType=INTEGER}
        where id = #{id,jdbcType=VARCHAR}
    </update>
</mapper>