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;
}

此方法有個短處,不適用與並發數較多的,這時候需要去校驗序號是否重復,最好的方法還是用單例模式的方式實現序號增長


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM