第一种方式:
首先,根据时间生成,我们先要格式化一下时间格式
SimpleDateFormat dmfot = new SimpleDateFormat("yyyyMMdd");
//截取当前时间作为流水号
String preCode = dmfot.format(new Date());
然后我们进行数据库查询,今天最大的流水号是多少?
//获取最大编号
String maxCode = getMaxCode(date);
查询语句如下:
select Max(code)
from table_name
where
declare_time >= STR_TO_DATE(#{date},'%Y-%m-%d')
这里我们重置一下时间格式,获取当前时间零点
/**
* 返回当前时间零点
* @return
*/
public static String getCurrentDay() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date date = c.getTime();
String currentDay = format.format(date);
return currentDay;
}
查询之后进行判断,如果查出的数据为空,证明今天没有生成流水号,我们直接set
//设置流水号格式,根据实际情况设置
DecimalFormat num=new DecimalFormat("000");
if(maxCode != null && !"null".equals(maxCode)){
//对流水号截取后三位
String code = maxCode.substring(maxCode.length()-3,maxCode.length());
//例如后三位为002,通过以下步骤,将会变为003
int count = Integer.valueOf(code)+1;
String number = num.format(count);
return preCode + "-" + number;
}else {
return preCode + "-" + "001";
}
"001";例如 20191017-001
第二种:
1、使用redis原子自增特性
2、先判断key,是否存在
2.1、存在:顺序码自增
2.2、不存子:重新生成顺序码
代码实现
控制器
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestContr