首先是SQL:
<select id="codeList" resultType="java.lang.String">
SELECT code
FROM 表名
WHERE EXTRACT(YEAR FROM CREATE_DATE) = EXTRACT(YEAR FROM CURRENT_DATE);
</select>
从表中选择那些其CREATE_DATE
字段所在年份与当前日期年份相等的记录的code
接下来是java部分的代码
private static textService textService;
@Autowired
public void setTextService(textService textService ) {
PrimaryIdGenerate.textService = textService ;
}
public synchronized String getYaPlanId() {
// code-202211200001
String ID_format = "code-%d%s";
String PrimaryCode = "";
List<Integer> codeList = Lists.newArrayList();
List<String> coderList = textService.planIdList();
if (coderList.size() == 0) {
String date = LocalDate.now().toString();
String replaced = date.replace("-", "");
PrimaryCode = String.format(ID_format, Integer.parseInt(replaced), "0001");
} else {
for (String str : coderList) {
String[] split = str.split("-");
String year = split[1];
String code = year.substring(year.length() - 4);
codeList.add(Integer.valueOf(code));
}
Integer max = Collections.max(codeList) + 1;
String format = String.format("%0" + 4 + "d", max);
String date = LocalDate.now().toString();
String replaced = date.replace("-", "");
PrimaryCode = String.format(ID_format, Integer.parseInt(replaced), format);
}
return PrimaryCode;
}
上述代码的流水号格式:code + 年月日 + 0001(四位自增流水号),可根据需求更改
至于如何调用,就是service直接点方法咯