自 3.3.0 開始,默認使用雪花算法+?UUID
?(不含中劃線)
自定義示例工程:
方法 | 主鍵生成策略 | 主鍵類型 | 說明 |
?nextId ? |
ASSIGN_ID, |
Long, Integer, String |
支持自動轉(zhuǎn)換為 String 類型,但數(shù)值類型不支持自動轉(zhuǎn)換,需精準匹配,例如返回 Long,實體主鍵就不支持定義為 Integer |
?nextUUID ? |
ASSIGN_UUID, |
String |
默認不含中劃線的 UUID 生成 |
@Component
public class CustomIdGenerator implements IdentifierGenerator {
@Override
public Long nextId(Object entity) {
//可以將當前傳入的class全類名來作為bizKey,或者提取參數(shù)來生成bizKey進行分布式Id調(diào)用生成.
String bizKey = entity.getClass().getName();
//根據(jù)bizKey調(diào)用分布式ID生成
long id = ....;
//返回生成的id值即可.
return id;
}
}
@Bean
public IdentifierGenerator idGenerator() {
return new CustomIdGenerator();
}
@Bean
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
return plusProperties -> plusProperties.getGlobalConfig().setIdentifierGenerator(new CustomIdGenerator());
}
<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;
}
更多建議: