mybatis-plus雪花算法生成Id使用詳解
前言
在實際開發(fā)過程中,數(shù)據(jù)庫自增主鍵生成Id能滿足大部分的場景。
但是隨著分布式應(yīng)用場景的增多,表數(shù)據(jù)的增大導(dǎo)致分表分庫的大量應(yīng)用。
數(shù)據(jù)庫自增主鍵的生成規(guī)則無法滿足對應(yīng)的業(yè)務(wù)場景,于是誕生了越來越多的分布式ID生成算法,其中雪花算法是目前最為流行的。
今天說一下在mybatis-plus中如何使用雪花算法生成Id。
一、mybatis-plus官網(wǎng)
Git地址:https://github.com/baomidou/mybatis-plus
TIP??:
推薦學(xué)習(xí)框架的使用的時候,都多研究下官網(wǎng),獲取第一手資料。
二、雪花算法實戰(zhàn)
1.建表
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主鍵ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年齡',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',
PRIMARY KEY (id)
);
注意??:
這里的主鍵字段沒有配置自增生成策略,所以執(zhí)行新增操作的時候,需要給id字段設(shè)置值,才能新增成功。類似如下:
INSERT INTO user ( id, name, age, email ) VALUES ( 123434, 'test', 13, '101@qq.com')

相關(guān)代碼:
maven依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
實體User:
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
mapper:
public interface UserMapper extends BaseMapper<User> {
}
啟動類Application:
@SpringBootApplication
@Slf4j
@MapperScan("com.laowan.mybatis_plus.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
log.info("mybatis_plus_demo 啟動成功");
}
}
注意??:
這里在啟動類上配置了@MapperScan(“mapper接口目錄”),所以在UserMapper接口上沒有條件@Mapper注解。
@Mapper配置方法:
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
兩者任意選擇一種方式配置即可,如果都不配置,那么在執(zhí)行dao層方法進(jìn)行數(shù)據(jù)操作時,會出現(xiàn)在spring容器中找不到對應(yīng)的bean的異常。
@Mapper和@MapperScan都不配置調(diào)用mapper方法時出現(xiàn)的異常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.laowan.mybatis_plus.mapper.UserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
配置屬性:
server.port=8080 logging.level.com.laowan.mybatis_plus.mapper=debug spring.datasource.url = jdbc:mysql://localst:3306/seckill?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true spring.datasource.username = root spring.datasource.password = 123456
3.測試
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert() {
System.out.println(("----- insert method test ------"));
User user = new User();
user.setName("test");
user.setAge(13);
user.setEmail("101@qq.com");
userMapper.insert(user);
System.out.println(user.toString());
}
執(zhí)行結(jié)果:

User(id=728666272023183375, name=test, age=13, email=101@qq.com)
多次執(zhí)行,發(fā)現(xiàn)主鍵ID的確呈趨勢遞增。

結(jié)論:
主鍵id的生成策略已經(jīng)采用了雪花算法,呈趨勢遞增。
三、實現(xiàn)分析
很多人可能疑惑??,你這明明啥都沒干,怎么就實現(xiàn)了雪花算法生成Id。
其實mybatis-plus已經(jīng)內(nèi)置雪花算法生成分布式唯一id。
在mybatis-plus特性中已經(jīng)明確說明了這點。

我們可以直接在IDEA中雙擊shift搜索Sequence類查看其具體實現(xiàn),可以發(fā)現(xiàn)其實現(xiàn)就是采用了雪花算法。

四、為什么默認(rèn)就是雪花算法
實體User:
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
這里可以看到我們并沒有在實體類的id上設(shè)置id生成策略。
其實mybatis-plus中默認(rèn)的主鍵生成策略為DefaultIdentifierGenerator,里面的實現(xiàn)就是采用Sequence生成主鍵。

public class DefaultIdentifierGenerator implements IdentifierGenerator {
private final Sequence sequence;
public DefaultIdentifierGenerator() {
this.sequence = new Sequence((InetAddress)null);
}
public DefaultIdentifierGenerator(InetAddress inetAddress) {
this.sequence = new Sequence(inetAddress);
}
public DefaultIdentifierGenerator(long workerId, long dataCenterId) {
this.sequence = new Sequence(workerId, dataCenterId);
}
public DefaultIdentifierGenerator(Sequence sequence) {
this.sequence = sequence;
}
public Long nextId(Object entity) {
return this.sequence.nextId();
}
}
五、主動設(shè)置Id生成策略
可以通過mybatis-plus中的@TableId主鍵,主動標(biāo)識主鍵字段,并配置主鍵生成策略。
@Data
public class User {
//采用IdentifierGenerator默認(rèn)的實現(xiàn)類DefaultIdentifierGenerator生成id
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String name;
private Integer age;
private String email;
}

總結(jié)
mybatis-plus已經(jīng)內(nèi)置了雪花算法生成分布式唯一Id,并且是默認(rèn)的ID生成策略。
大家在實際項目中,可以通過在主鍵字段上添加@TableId注解來控制主鍵的生成策略。
到此這篇關(guān)于mybatis-plus雪花算法生成Id使用詳解的文章就介紹到這了,更多相關(guān)mybatis-plus雪花生成Id內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot基于Redis實現(xiàn)token的在線續(xù)期的實踐
本文主要介紹了使用Redis實現(xiàn)JWT令牌在線續(xù)期的方案,通過在線續(xù)期token,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12
Nacos docker單機模式部署實現(xiàn)過程詳解
這篇文章主要介紹了Nacos docker單機模式部署實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
idea快速搭建spring cloud注冊中心與注冊的方法
這篇文章主要介紹了idea快速搭建spring cloud注冊中心與注冊的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
Spring 應(yīng)用上下文獲取 Bean 的常用姿勢實例總結(jié)
這篇文章主要介紹了Spring 應(yīng)用上下文獲取 Bean,結(jié)合實例形式總結(jié)分析了Spring 應(yīng)用上下文獲取 Bean的實現(xiàn)方法與操作注意事項,需要的朋友可以參考下2020-05-05
如何在SpringBoot中使用logback優(yōu)化異常堆棧的輸出詳解
最近項目中整合了logback,所以下面這篇文章主要給大家介紹了關(guān)于如何在SpringBoot中使用logback優(yōu)化異常堆棧的輸出,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
SpringBoot如何使用MyBatis-Plus實現(xiàn)高效的數(shù)據(jù)訪問層
在開發(fā) Spring Boot 應(yīng)用時,數(shù)據(jù)訪問是不可或缺的部分,本文將詳細(xì)介紹如何在 Spring Boot 中使用 MyBatis-Plus,并結(jié)合具體代碼示例來講解它的使用方法和常見配置,希望對大家有一定的幫助2025-04-04

