自 3.3.0 开始,默认使用雪花算法+UUID(不含中划线)
IdType{
AUTO(0),数据库ID自增 该类型请确保数据库设置了ID自增 否则无效
NONE(1),该类型为未设置主键类型(注解里等于跟随全局,全局里约等INPUT)
INPUT(2),用户输入ID该类型可以通过自己注册自动填充插件进行填充
ASSIGN_ID(3),分配ID (主键类型为number或string)雪花算法
ASSIGN_UUID(4);分配UUID (主键类型为 string)
}
NONE,INPUT,都需要自己手动设置主键id
Spring-Boot配置通过 MybatisPlusPropertiesCustomizer 自定义
1.配置SnowflakeUtils
package com.lyj.demo.Handler;
public class SnowflakeUtils {
private final static long START_STMP = 1567267200000L;//2019-09-01 00:00:00
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 8; //机器标识占用的位数,256个机器
private final static long DATACENTER_BIT = 2;//数据中心占用的位数,4个数据中心
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //数据中心
private long machineId; //机器标识
private long sequence = 0L; //序列号
private long lastStmp = -1L;//上一次时间戳
public SnowflakeUtils(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than "+MAX_DATACENTER_NUM+" or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than "+MAX_MACHINE_NUM+" or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
//循环获取多几次,尽可能地避免不可能的可能
for(int i = 0; i< 100; i ++){
currStmp = getNextMill();
if (currStmp != lastStmp){
break;
}
}
}
} else {
//不同毫秒内,序列号置为0
sequence = 0L;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
| datacenterId << DATACENTER_LEFT //数据中心部分
| machineId << MACHINE_LEFT //机器标识部分
| sequence; //序列号部分
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
public static long getId() {
SnowflakeUtils idGenerator = new SnowflakeUtils(1, 1);
return idGenerator.nextId();
}
public static void main(String[] args) {
SnowflakeUtils snowFlake = new SnowflakeUtils(1, 1);
long start = System.currentTimeMillis();
System.out.println(snowFlake.nextId());
System.out.println(System.currentTimeMillis() - start);
}
}
2.创建CustomIdGenerator类 implements IdentifierGenerator
让spring识别
@Component 一定不要忘记把处理器加入到ioc容器中
package com.lyj.demo.Handler;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import org.springframework.stereotype.Component;
import java.util.Random;
//让spring识别
@Component //一定不要忘记把处理器加入到ioc容器中
public class CustomIdGenerator implements IdentifierGenerator {
private final char[] arrays = {
'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
};
private final Random random = new Random();
@Override
public Number nextId(Object entity) {
return SnowflakeUtils.getId();
}
@Override
public String nextUUID(Object entity) {
StringBuffer buffer = new StringBuffer();
String name = entity.getClass().getSimpleName().toLowerCase();
buffer.append(name).append("-");
for (int i = 0; i < 9; i++) {
buffer.append(arrays[random.nextInt(26) + 10]);
buffer.append(arrays[random.nextInt(10)]);
}
return buffer.toString();
}
}
3.配置MybatisPlusConfig类
springboot启动类中@MapperScan(“com.lyj.demo.mapper”)可以写到
MybatisPlusConfig类 这里
@MapperScan(“com.lyj.demo.mapper”)
@Configuration
自定义ID 生成器 方式二 2.1雪花算法生成19字符长度主键Id
//注入spring容器
@MapperScan("com.lyj.demo.mapper")
@Configuration
public class MybatisPlusConfig {
//自定义ID 生成器 方式二 2.1雪花19字符串
@Bean
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
return plusProperties -> plusProperties.getGlobalConfig().
setIdentifierGenerator(new CustomIdGenerator());
}
//2.1雪花16字符串
// @Bean
// public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
// return plusProperties -> plusProperties.getGlobalConfig().
// setIdentifierGenerator(new CustomIdGenerator2());
// }
}
4.配置SpringBootApplication启动类扫描自己配置的config
@ComponentScan(basePackages = {"com.lyj.demo.config"})
//@MapperScan("com.lyj.demo.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
5.在实体类User表配置IdType
@TableId(type =IdType.ASSIGN_ID )
private Long id;
6.到测试类测试



