工作中要求合同編號自動生成 格式 NYZL-001,NYZL-002。。。在我的StringUtils工具類中新增如下方法,該方法可以自定義前綴以及當前排到數字幾了(可從數據庫中查詢最大的編號+1)
/**
* 自動生成編號
* @param prefix 前綴,往往是一串字符串
* @param nowNum 當前要生成的數字
* @return
*/
public static 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, "cId", 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);
}
}