一般有时候我们需要生成唯一主键id,如果数据库是mysql我们可以使用主键自增,如果是oracle我们可以创建触发器或者序列,如果不借助数据库我们也可以在java层面自己生成唯一主键。
- 使用随机数:
/*
生成唯一主键
格式:时间+随机数
*/
public static String genUniqueKey() {
Random random = new Random();
Integer number = random.nextInt(900000) + 100000;
return System.currentTimeMillis() + String.valueOf(number);
}
- 使用UUID
public static String getUUID(){
UUID uuid=UUID.randomUUID();
String uuidStr=uuid.toString();
return uuidStr;
}