按年月日时分秒+自增序号的一种数据库主键生成策略

来源:互联网 发布:u盘数据恢复免费软件 编辑:程序博客网 时间:2024/05/03 11:20

当年月日时分秒相同时,其后序号自增。

 

1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
import java.text.SimpleDateFormat;
import java.util.Date;
public class Key {
private static String previousTime = "";
private static Integer ORDER = 0;
/**
* 获取年月日时分秒+随机数主键值
* @return
*/
public static String getKeyValue(){
String currentTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String keyValue = currentTime;
if(currentTime.equals(previousTime)){
ORDER++;
StringBuffer orderStr = new StringBuffer("");
for(int i=0;i<6-ORDER.toString().length();i++){
orderStr.append("0");
}
orderStr.append(ORDER.toString());
keyValue += orderStr;
}else{
previousTime = currentTime;
ORDER = 1;
StringBuffer orderStr = new StringBuffer("");
for(int i=0;i<6-ORDER.toString().length();i++){
orderStr.append("0");
}
orderStr.append(ORDER.toString());
keyValue += orderStr;
}
return keyValue;
}
public static void main(String[] args){
for(int i=0;i<1000000;i++){
System.out.println(Key.getKeyValue());
}
}
}

 

0 0
原创粉丝点击