MyBatis-Plus 核心功能-自定义ID生成器

提示

自 3.3.0 开始,默认使用雪花算法+​UUID​(不含中划线)

自定义示例工程:

 方法 主键生成策略 主键类型 说明
nextIdASSIGN_ID,
ID_WORKER
ID_WORKER_STR
Long,
Integer,
String
支持自动转换为 String 类型,但数值类型不支持自动转换,需精准匹配,例如返回 Long,实体主键就不支持定义为 Integer
nextUUIDASSIGN_UUID,UUIDString默认不含中划线的 UUID 生成

Spring-Boot

方式一:声明为 Bean 供 Spring 扫描注入

@Component
public class CustomIdGenerator implements IdentifierGenerator {
    @Override
    public Long nextId(Object entity) {
      	//可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
      	String bizKey = entity.getClass().getName();
        //根据bizKey调用分布式ID生成
        long id = ....;
      	//返回生成的id值即可.
        return id;
    }
}

方式二:使用配置类

@Bean
public IdentifierGenerator idGenerator() {
    return new CustomIdGenerator();
}

方式三:通过 MybatisPlusPropertiesCustomizer 自定义

@Bean
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
    return plusProperties -> plusProperties.getGlobalConfig().setIdentifierGenerator(new CustomIdGenerator());
}

Spring

方式一: XML 配置

<bean name="customIdGenerator" class="com.baomidou.samples.incrementer.CustomIdGenerator"/>

<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
		<property name="identifierGenerator" ref="customIdGenerator"/>
</bean>

方式二:注解配置

@Bean
public GlobalConfig globalConfig() {
	GlobalConfig conf = new GlobalConfig();
	conf.setIdentifierGenerator(new CustomIdGenerator());
	return conf;
}

作者:冒牌SEO,如若转载,请注明出处:https://www.web176.com/mybatis-plus/20390.html

(0)
打赏 支付宝 支付宝 微信 微信
冒牌SEO冒牌SEO
上一篇 2023年5月16日
下一篇 2023年5月16日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注