关于myBatisPlus,相信大部分小伙伴们并不陌生。
myBatisPlus主键生成策略,其实并不复杂。
我们可以在实体类的id上面加一下注解:
@TableId(type = IdType.AUTO)
private Long id;
@TableId注解属于myBatisPlus中的,当点开type后会发现
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface TableId {
String value() default "";
IdType type() default IdType.NONE;
}
含有两个属性,其中**type()**是一个枚举类型,点进去可以看到
public enum IdType {
AUTO(0),
NONE(1),
INPUT(2),
ID_WORKER(3),
UUID(4),
ID_WORKER_STR(5);
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
看到这里,就简洁明了了,myBatisPlus中定义了6个主键生成的策略,如果希望数据库自增的话那就AUTO,一般情况下使用ID_WORKEY雪花算法生成主键。
然后有小伙伴会问了,这样的话是不是每创建一个实体类就要加一个这样的注解。
理论上是这样的,当然,如果想简便的话,这里就推荐配置一个全局的主键生成策略。
在springBoot中,只需在yml文件中如下配置:
mybatis-plus:
global-config:
db-config:
id-type: id_worker
其中id-type就是上面所说到的枚举类型。