文章目錄
- 前言
- 一、如何自定義
- 二、Spring Boot 集成
- 1. 方式一:聲明為Bean供Spring掃描注入
- 2. 方式二:使用配置類
- 3. 方式三:通過MybatisPlusPropertiesCustomizer自定義
- 三、Spring 集成
- 1. 方式一:XML配置
- 2. 方式二:注解配置
- 四、與KeyGenerator的差異
- 總結
前言
MyBatis-Plus 提供了靈活的自定義ID生成器功能,允許開發者根據業務需求定制ID生成策略。從3.3.0版本開始,默認使用雪花算法結合不含中劃線的UUID作為ID生成方式。
MyBatis-Plus自帶主鍵生成策略對比
方法 | 主鍵生成策略 | 主鍵類型 | 說明 |
---|---|---|---|
nextId | ASSIGN_ID | Long,Integer,String | 支持自動轉換為String類型,但數值類型不支持自動轉換,需精準匹配,例如返回Long,實體主鍵就不支持定義為Integer |
nextUUID | ASSIGN_UUID | String | 默認不含中劃線的UUID生成 |
一、如何自定義
MyBatis-Plus 提供了多種方式來實現自定義ID生成器,以下是一些示例工程和配置方法。
二、Spring Boot 集成
1. 方式一:聲明為Bean供Spring掃描注入
@Component
public class CustomIdGenerator implements IdentifierGenerator {@Overridepublic Long nextId(Object entity) {// 使用實體類名作為業務鍵,或者提取參數生成業務鍵String bizKey = entity.getClass().getName();// 根據業務鍵調用分布式ID生成服務long id = ...; // 調用分布式ID生成邏輯// 返回生成的ID值return id;}
}
2. 方式二:使用配置類
@Bean
public IdentifierGenerator idGenerator() {return new CustomIdGenerator();
}
3. 方式三:通過MybatisPlusPropertiesCustomizer自定義
@Bean
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {return plusProperties -> plusProperties.getGlobalConfig().setIdentifierGenerator(new CustomIdGenerator());
}
三、Spring 集成
1. 方式一:XML配置
<bean name="customIdGenerator" class="com.example.CustomIdGenerator"/>
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig"><property name="identifierGenerator" ref="customIdGenerator"/>
</bean>
2. 方式二:注解配置
@Bean
public GlobalConfig globalConfig() {GlobalConfig conf = new GlobalConfig();conf.setIdentifierGenerator(new CustomIdGenerator());return conf;
}
四、與KeyGenerator的差異
MyBatis-Plus
的IdentifierGenerator
主要用于生成數據庫表的主鍵ID,而KeyGenerator
是MyBatis
框架中的一個接口,用于在執行SQL語句時生成鍵值,通常用于生成自增主鍵或者在執行INSERT語句后獲取新生成的ID。
IdentifierGenerator
更加專注于主鍵ID的生成,而KeyGenerator
則更加通用,可以用于多種鍵值生成場景。在使用MyBatis-Plus
時,通常推薦使用IdentifierGenerator
來生成主鍵ID,因為它與MyBatis-Plus
的集成更加緊密,提供了更多的便利性和功能。
總結
回到頂部