工作中要求合同编号自动生成 格式 NYZL-001,NYZL-002。。。在我的StringUtils工具类中新增如下方法,该方法可以自定义前缀以及当前排到数字几了(可从数据库中查询最大的编号+1)
/*** 自动生成编号* @param prefix 前缀,往往是一串字符串* @param nowNum 当前要生成的数字* @return*/public static synchronized String getConteactNo(String prefix,int nowNum ) {StringBuilder builder = new StringBuilder();StringBuilder num = new StringBuilder();AtomicInteger count = new AtomicInteger(nowNum);// 4位数字的采取编号处理。9999的情况下从001开始采取。if (count.get() > 9999) {count = new AtomicInteger(1);}// 采用4位数的数字进行序号处理。if (count.get() < 10) {num.append("00").append(count.getAndIncrement());} else if (count.get() >= 100) {num.append(count.getAndIncrement());} else {num.append("0").append(count.getAndIncrement());}// 组合。builder.append(prefix);builder.append(num);return builder.toString();}
保存时,将数据库最大编号查出,然后+1设置到工具类即可
int id = ParamUtils.getInt(request, "contractId", 0);if (id == 0) {//新增String maxNo = this.contractManager.selectMaxContractNo();if (maxNo != null) {String[] split = maxNo.split("-");String contractNo = StringUtils.getConteactNo("NYZL-", Integer.valueOf(split[1]) + 1);contract.setContractNo(contractNo);} else {String contractNo = StringUtils.getConteactNo("NYZL-", 1);contract.setContractNo(contractNo);}}