接口方法:
Integer getCode(IncomeAllot incomeAllot);
service层代码:
public String getCode(){
String code = "";
//日期处理类
String year = DateUtils.getYear();
String month = DateUtils.getMonth();
code = "F" + year + month+"-";
IncomeAllot ia = new IncomeAllot();
//mapping中SQL语句有条件,这必须传入值
ia.setCode(code);
//最上层接口中定义持久层对象dao
Integer num = dao.getCode(ia);
DecimalFormat df = new DecimalFormat("000");
code = code + df.format(num);
return code;
}
Mapping映射文件:
<select id="getCode" resultType="Integer">
SELECT
<!-- 查询年月对应编号出现的下一个数字,返回该数字-->
NVL(MAX(TO_NUMBER(SUBSTR(a.code,INSTR(a.code,'-')+1))),0)+1
FROM income_allot a
<!-- 模糊查询对应年月的编号,可以做到不同的年和月能从001开始编号-->
WHERE a.code like '%'||#{code}||'%'
</select>
注:用的oracle数据库。
总结:最核心的就是映射文件中查询条件,根据后台传来的年月,查询对应的编号,相同的日期顺序编号,不同的日期从1开始编号。service中定义的getCode不需要参数。获取年月字符串后必须要设置,该方法只返回生成的编号,并没有将编号存入的数据库中。