MyBatis-Plus Sequence主键的实现
这篇文章主要介绍了MyBatis-Plus Sequence主键的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Sequence主键是什么:
序列(SEQUENCE)是序列号生成器,可以为表中的行自动生成序列号,产生一组等间隔的数值(类型为数字)。不占用磁盘空间,占用内存。
其主要用途是生成表的主键值,可以在插入语句中引用,也可以通过查询检查当前值,或使序列增至下一个值。
MP内置支持的数据库主键策略:
1.DB2KeyGenerator
2.H2KeyGenerator
3.KingbaseKeyGenerator
4.OracleKeyGenerator
5.PostgreKeyGenerator
mybatis plus 实体类主键策略有3种( 注解 > 全局 > 默认 )
**注解使用**
@KeySequence(value = "seq_emp",clazz = String.class)
@TableName("EMP")
public class Emp {
@TableId(type = IdType.INPUT)
private String eid;
private String ename;
}
IdType
AUTO:数据库ID自增
INPUT:用户输入ID
NONE:该类型为未设置主键类型,注解里等于跟随全局,全局里约等于 INPUT
ASSIGN_ID:使用雪花算法分配ID,主键类型为Number(Long和Integer)或String
ASSIGN_UUID:分配UUID,主键类型为String
ID_WORKER:分布式全局唯一ID 长整型类型,已弃用
UUID:UUID:32位UUID字符串,已弃用
ID_WORKER_STR:分布式全局唯一ID 字符串类型,已弃用
spring boot
支持主键类型指定(3.3.0开始自动识别主键类型)
方式一:使用配置类
@Bean
public IKeyGenerator keyGenerator() {
return new OracleKeyGenerator();
}
方式二:通过MybatisPlusPropertiesCustomizer自定义
@Bean
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
return plusProperties -> plusProperties.getGlobalConfig().getDbConfig().setKeyGenerator(new OracleKeyGenerator());
}
Spring
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig" ref="dbConfig"/>
</bean>
<bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
<property name="keyGenerator" ref="keyGenerator"/>
</bean>
<bean id="keyGenerator" class="com.baomidou.mybatisplus.extension.incrementer.OracleKeyGenerator"/>
方式二:注解配置
@Bean
@Bean
public GlobalConfig globalConfig() {
GlobalConfig conf = new GlobalConfig();
conf.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerator(new OracleKeyGenerator()));
return conf;
}