MyBatis-Plus Sequence主键

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

  1. DB2KeyGenerator
  2. H2KeyGenerator
  3. KingbaseKeyGenerator
  4. OracleKeyGenerator
  5. PostgreKeyGenerator

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;
}
发布了29 篇原创文章 · 获赞 0 · 访问量 372

猜你喜欢

转载自blog.csdn.net/qq_43399077/article/details/104061797