1. 程式人生 > 實用技巧 >java如何自動設定資料庫自增長編號

java如何自動設定資料庫自增長編號

假設增長編號方式為 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;
}