java新增后生成一定规则的流水号,字符串+当前日期+递增序号

我的业务需求:
生成编号规则为 HSJC-年月日01、02、03一直累加如下图所示。
默认为:HSJC-yyyyMMdd01
在这里插入图片描述
在网上找了很多解决方案,个人觉得不太行,特地总结一下:

1、写一个递增编号的方法

/**
     * 轮次编号生成规则
     * 1、如果当前时间没有核酸轮次,直接新增 ,默认为:HSJC-yyyyMMdd01
     * 2、查询到有核酸轮次,查找当前那一天最大的轮次编号,自增1
     *
     * @param code 当前最大编码
     */
    public static String getNum(String code) {
    
    
        String roundCode = "01";
        if (code != null && !code.isEmpty()) {
    
    
            int intCode = Integer.parseInt(code) + 1;
            if (intCode < 99) {
    
    
                roundCode = String.format(String.valueOf(intCode));
            } else {
    
    
                throw new BusinessException(Result.exception("500", "轮次编号达到最大"));
            }
        }
        //编号前面补0
        DecimalFormat df = new DecimalFormat("00");
        String newCode = df.format(Integer.parseInt(roundCode));
        return newCode;
    }

2、在业务代码中调用getNum这个方法,实现如下:

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String code = "HSJC-" + df.format(new Date());
        //模糊查询当前最大的编号
        String maxCode = roundsManager.maxRoundCode(code);
        String newCode = null;
        if (StringUtils.isEmpty(maxCode)) {
    
    
            newCode = code + "01";
        } else {
    
    
        //切割字符串,取查到编号的最后两位
            String getMaxCode = maxCode.substring(13, 15);
            newCode = code + getNum(getMaxCode);
        }
        hsRounds.setCode(newCode);

其中上面的

String maxCode = roundsManager.maxRoundCode(code);

语句对应的sql为:

<select id="maxRoundCode" resultType="java.lang.String">
        select max(code) from table1 where code like concat(#{
    
    nowTime},'%')
 </select>

表部分截图如下:
在这里插入图片描述
到此结束:

个人思路:
1、编号为字符串,将日期和字符串进行拼接,简化问题为“编号递增”
a)如果当前数据库中没有记录,就按默认值来取:默认为:HSJC-yyyyMMdd01
b)如果已经存在记录,查询当前编号的后两位,进行+1 2、写一个编号递增方法

猜你喜欢

转载自blog.csdn.net/victo_chao/article/details/120438648