假设增长编号方式为 FE202002020001 即:FE+年月日+四位序号
dao层 :
public class CmsFinancialInfoDao{
/**获取最新的编号*/
public String getFinancialInfoMaxCode(String dayStr){
String sql = "select max(e.expense_code) from cms_financial_expense e where e.expense_code like '"+FinancialConstant.FINANCIAL_INFO_CODE+dayStr+"%'";
Object maxCode = this.getSession().createSQLQuery(sql).uniqueResult();
if (!EmptyUtils.isEmpty(maxCode)){
return maxCode.toString();
}
return null;
}
}
service层:
public String getSequence(){
int number = 0;
String voucherNumber = "";
String dayStr = DateUtils.format(new Date(),"yyyyMMdd");
voucherNumber = cmsFinancialInfoDao.getFinancialInfoMaxCode(dayStr);
if(EmptyUtils.isEmpty(voucherNumber)){
voucherNumber = FinancialConstant.EXPEMSE_CODE+dayStr+"0001";
}else{
number = Integer.parseInt(voucherNumber.substring(10,14));//截取最后四位
number++;
voucherNumber = "FE"+dayStr+String.format("%04d",number);
}
return voucherNumber;
}
此方法有个短处,不适用与并发数较多的,这时候需要去校验序号是否重复,最好的方法还是用单例模式的方式实现序号增长