策略在枚举类IdType 中,有五种
public enum IdType {
AUTO(0),//数据库自增 依赖数据库
NONE(1),// 表示该类型未甚至主键类型 (如果没有主键策略)默认根据雪花算法生成一个Long类型值
INPUT(2),//用户输入ID(该类型可以通过自己注册填充插件进行填充)
//下面这三种类型,只有当插入对象id为空时 才会自动填充。
ID_WORKER(3),//全局唯一(idWorker)数值类型
UUID(4),//全局唯一(UUID)
ID_WORKER_STR(5);//全局唯一(idWorker的字符串表示)
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
如何设置主键策略
1,局部主键策略实现
在实体类中 ID属性加注解
@TableId(type = IdType.AUTO) 主键自增 数据库中需要设置主键自增
private Long id;
@TableId(type = IdType.NONE) 默认 跟随全局策略走
private Long id;
@TableId(type = IdType.UUID) UUID类型主键
private Long id;
@TableId(type = IdType.ID_WORKER) 数值类型 数据库中也必须是数值类型 否则会报错
private Long id;
@TableId(type = IdType.ID_WORKER_STR) 字符串类型 数据库也要保证一样字符类型
private Long id;
@TableId(type = IdType.INPUT) 用户自定义了 数据类型和数据库保持一致就行
private Long id;
2,全局主键策略实现
在application.yml文件中设置
mybatis-plus:
mapper-locations:
- com/mp/mapper/*
global-config:
db-config:
id-type: uuid/none/input/id_worker/id_worker_str/auto #表示全局主键都采用该策略
遇到的坑, 写本文缘由
场景:
- 在数据库中, 主键id设置为自增长
- 在java代码实体类中,与数据库主键对应的属性没有指定主键策略
@TableId
private Integer id;
异常:
Could not set property 'id' of 'class com.xxx.xxx.xxx.api.entity.MqRecord' with value '1286526596646125569'
Cause: java.lang.IllegalArgumentException:
分析
其实原因在本文前面以及说了, 就是因为我在实体类中没有指定主键生成策略,于是mybatis-plus使用默认的雪花算法生成了一个Long类型的主键1286526596646125569
, 该值超过了实体类中id的Integer类型的范围, 于是就报错了.
解决方案
设置该实体类的id属性生成策略为自增长
@TableId(type = IdType.AUTO)
private Integer id;
感谢以下大佬的帮助:
参考资料: https://blog.csdn.net/u010514052/article/details/81775595