首页 > 编程技术 > java

MyBatis-Plus Sequence主键的实现

发布时间:2020-12-24 08:29

Sequence主键是什么:

序列(SEQUENCE)是序列号生成器,可以为表中的行自动生成序列号,产生一组等间隔的数值(类型为数字)。不占用磁盘空间,占用内存。

其主要用途是生成表的主键值,可以在插入语句中引用,也可以通过查询检查当前值,或使序列增至下一个值。

MP内置支持的数据库主键策略:

mybatis plus 实体类主键策略有3种( 注解 > 全局 > 默认 )

注解使用

public class User extends Model<User> {

  @TableId(value = "id", type = IdType.AUTO)
  private String id;

  @TableField("real_name")
  private String realName;
}

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 H2KeyGenerator();
}

方式二:通过MybatisPlusPropertiesCustomizer自定义

@Bean
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
  return plusProperties -> plusProperties.getGlobalConfig().getDbConfig().setKeyGenerator(new H2KeyGenerator());
}

Spring

方式一: XML配置

<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.H2KeyGenerator"/>

方式二:注解配置

@Bean
public GlobalConfig globalConfig() {
 GlobalConfig conf = new GlobalConfig();
 conf.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerator(new H2KeyGenerator()));
 return conf;
}

到此这篇关于MyBatis-Plus Sequence主键的实现的文章就介绍到这了,更多相关MyBatis-Plus Sequence主键内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: