首先数据库做了分表, 就不能是普通的生成自增主键, 因为多个分表主键会相同
此时可以选择uuid生成的string主键
例如:
public static synchronized String getUniqueKey() {
Random random = new Random();
Integer number = random.nextInt(900000) + 100000;
return System.currentTimeMillis() + String.valueOf(number);
}
也可以选择雪花算法生成long类型主键, 以保证分布式主键唯一
同时, 为了防止网址前端取主键时精度丢失(ps: 前端number类型16位, 后端long类型19位, 多出的三位精度会丢失)
需要:
@TableId(type = IdType.ASSIGN_ID) // 分表自动生成id
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
其中@TableId(type = IdType.ASSIGN_ID)表示雪花生成弄long类型id
@JsonSerialize(using = ToStringSerializer.class)表示传给前端时会序列化成字符串(防止精度丢失)
ps: 数据库不用string类型主键因为会导致索引失效