Quick Quick
首页
  • 快速入门
  • 功能模块
  • 后端规范
  • 代码生成器配置新
  • 代码生成器配置旧
问答
💖支持
更新日志 (opens new window)
GitHub (opens new window)
首页
  • 快速入门
  • 功能模块
  • 后端规范
  • 代码生成器配置新
  • 代码生成器配置旧
问答
💖支持
更新日志 (opens new window)
GitHub (opens new window)
  • 快速入门

    • 简介
    • 快速开始
    • 安装
    • 配置
    • 注解
    • 快速测试
  • 功能模块

    • MVC功能
    • 代码生成器(旧)
    • CRUD 接口
    • 条件构造器
    • 主键策略
    • 自定义ID生成器
      • Spring-Boot
        • 方式一:声明为 Bean 供 Spring 扫描注入
        • 方式二:使用配置类
        • 方式三:通过 MybatisPlusPropertiesCustomizer 自定义
      • Spring
        • 方式一: XML 配置
        • 方式二:注解配置

自定义ID生成器

提示

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

自定义示例工程:

  • spring-boot 示例 :传送门 (opens new window)
方法 主键生成策略 主键类型 说明
nextId ASSIGN_ID,ID_WORKER,ID_WORKER_STR Long,Integer,String 支持自动转换为 String 类型,但数值类型不支持自动转换,需精准匹配,例如返回 Long,实体主键就不支持定义为 Integer
nextUUID ASSIGN_UUID,UUID String 默认不含中划线的 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;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

# 方式二:使用配置类

@Bean
public IdentifierGenerator idGenerator() {
    return new CustomIdGenerator();
}
1
2
3
4

# 方式三:通过 MybatisPlusPropertiesCustomizer 自定义

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

# 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>
1
2
3
4
5

# 方式二:注解配置

@Bean
public GlobalConfig globalConfig() {
	GlobalConfig conf = new GlobalConfig();
	conf.setIdentifierGenerator(new CustomIdGenerator());
	return conf;
}
1
2
3
4
5
6
帮助我们改善此页面! (opens new window)
主键策略

← 主键策略

Theme by Vdoing | Copyright © 2016-2022 Team Baomidou | Sponsored by JetBrains | 渝ICP备2021000141号

友情链接:AiZuDa | D.Yang | NanCheung | apidocsBlog

  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×