自学内容网 自学内容网

Java-根据前缀-日期-数字-生成流水号(不重复)

🎈边走、边悟🎈迟早会好

小伙伴们在日常开发时可能会遇到的业务-生成流水号,在企业中可以说是比较常见的需求,

可以采用"前缀+日期+数字"的方式(ps:此方式是需要用到缓存的)
前缀:为了更好的标识这个流水号是属于哪种类型;
日期:为了防止重复;
数字:为了表示当前的流水所处序号。

SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
//todo  替换自己想要的前缀
String code = "xicui-" + df.format(new Date());
//模糊查询当前最大的编号
String maxCode = baseMapper.maxRoundCode(code);
String newCode = null;
if (StringUtils.isEmpty(maxCode)) {
    newCode = code + "-01";
} else {
    //切割字符串,取查到编号的最后两位
    String getMaxCode = maxCode.substring(maxCode.length()-2,maxCode.length());
    newCode = code + "-"+getNum(getMaxCode);
}

编号生成的方法-直接复制即可 

//编号生成
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 RuntimeException("500轮次编号达到最大");
        }
    }
    //编号前面补0
    DecimalFormat df = new DecimalFormat("00");
    String newCode = df.format(Integer.parseInt(roundCode));
    return newCode;
}

 模糊查询sql

select max(serial_number) from admission where serial_number like concat(#{code},'%')

 

 🌟感谢支持 听忆.-CSDN博客

🎈众口难调🎈从心就好


原文地址:https://blog.csdn.net/weixin_64296810/article/details/140696623

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!