mybatisplus使用雪花id通过swagger返回ID时精度丢失问题

xml 复制代码
在使用mybatisplus自带雪花的时候会发现返回的ID是19位的长度,因此在通过swagger页面展示的时候会发现后端返回的和页面展示的ID不一致问题。是因为精度丢失的问题。因此需要更改雪花ID的长度


xml 复制代码
跟踪进去:


发现是DefaultIdentifierGenerator类实现了IdentifierGenerator并重写了nextId方法,因此需要我们重写nextId方法

  • 进行重写:
java 复制代码
package com.ssdl.config.automatic;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.ssdl.util.IdGenerator;
import org.springframework.stereotype.Component;

@Component
public class CustomerIdGenerator implements IdentifierGenerator {
    @Override
    public Number nextId(Object entity) {
        return IdGenerator.generateId();
    }
}
java 复制代码
package com.ssdl.util;

import java.util.Date;
import java.util.UUID;
 
/**
 * compressed id generator, result id not great than 53bits before 2318-06-04.
 */
public class IdGenerator {
 
    private static IdGenerator instance = new IdGenerator(0);
 
    public static IdGenerator initDefaultInstance(int machineId) {
        instance = new IdGenerator(machineId);
        return instance;
    }
 
    public static IdGenerator getInstance() {
        return instance;
    }
 
    public static long generateId() {
        return instance.nextId();
    }
 
    // total bits=53(max 2^53-1:9007199254740992-1)
 
    // private final static long TIME_BIT = 40; // max: 2318-06-04
    private final static long MACHINE_BIT = 5; // max 31
    private final static long SEQUENCE_BIT = 8; // 256/10ms
 
    /**
     * mask/max value
     */
    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 TIMESTMP_LEFT = MACHINE_BIT + SEQUENCE_BIT;
 
    private long machineId;
    private long sequence = 0L;
    private long lastStmp = -1L;
 
    private IdGenerator(long machineId) {
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException(
                    "machineId can't be greater than " + MAX_MACHINE_NUM + " or less than 0");
        }
        this.machineId = machineId;
    }
 
    /**
     * generate new ID
     *
     * @return
     */
    public synchronized long nextId() {
        long currStmp = getTimestamp();
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
 
        if (currStmp == lastStmp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0L) {
                currStmp = getNextTimestamp();
            }
        } else {
            sequence = 0L;
        }
 
        lastStmp = currStmp;
 
        return currStmp << TIMESTMP_LEFT //
                | machineId << MACHINE_LEFT //
                | sequence;
    }
 
    private long getNextTimestamp() {
        long mill = getTimestamp();
        while (mill <= lastStmp) {
            mill = getTimestamp();
        }
        return mill;
    }
 
    private long getTimestamp() {
        // per 10ms
        return System.currentTimeMillis() / 10;// 10ms
    }
 
    public static Date parseIdTimestamp(long id) {
        return new Date((id >>> TIMESTMP_LEFT) * 10);
    }
 
    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

插曲:

在使用mybatisplus时自动插入创建时间之类的操作:

java 复制代码
package com.ssdl.config.autoMatic;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MybatisHandler implements MetaObjectHandler {
	@Override
	public void insertFill(MetaObject metaObject) {
		//属性名
		this.setFieldValByName("createTime", new Date(), metaObject);
		this.setFieldValByName("updateTime", new Date(), metaObject);
		this.setFieldValByName("isDel", 0, metaObject);
		this.setFieldValByName("createUser", "admin", metaObject);
		this.setFieldValByName("updateUser", "admin", metaObject);
		//this.setFieldValByName("createUser", SecureUtil.getUserId(), metaObject);
        //不维护create_user可以不使用这行代码
	}
 
	@Override
	public void updateFill(MetaObject metaObject) {
		//属性名
		this.setFieldValByName("updateTime", new Date(), metaObject);
		this.setFieldValByName("updateUser", "admin", metaObject);
		//this.setFieldValByName("updateUser", SecureUtil.getUserId(), metaObject);
	}
}
java 复制代码
	@TableId(value = "id",type = IdType.ASSIGN_ID)
    private Long id;

    /**
     * 进行新增或者更新操作时
     * Mybatis自动进行维护时间
     */
    @TableField(fill= FieldFill.INSERT)
    private String createUser;

    @TableField(fill=FieldFill.INSERT)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;

    @TableField(fill=FieldFill.INSERT_UPDATE)
    @JsonIgnore
    private String updateUser;

    @TableField(fill= INSERT_UPDATE)
    @JsonIgnore
    private Date updateTime;

    @TableLogic
    @TableField(fill= FieldFill.INSERT)
    @JsonIgnore
    private Integer isDel;
相关推荐
jinanwuhuaguo2 分钟前
(第三十六篇)OpenClaw 去中心化的秩序——从“中心调度”到“网格自治”的治理革命
java·大数据·开发语言·网络·docker·去中心化·github
AI进化营-智能译站5 小时前
ROS2 C++开发系列17-多线程驱动多传感器|chrono高精度计时实现机器人同步控制
java·c++·ai·机器人
qq_589568108 小时前
springbootweb案例,出现访问 http://localhost:8080/list 一直处于浏览器运转阶段
java·网络协议·http·list·springboot
JAVA面经实录9179 小时前
计算机基础(完整版·超详细可背诵)
java·linux·数据结构·算法
AC赳赳老秦9 小时前
知识产权辅助:用 OpenClaw 批量生成专利交底书 / 软著申请材料,自动校验格式与内容合规性
java·人工智能·python·算法·elasticsearch·deepseek·openclaw
FYKJ_201010 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
书源丶11 小时前
三十六、File 类与 IO 流基础——文件操作的「第一步」
java
AI人工智能+电脑小能手11 小时前
【大白话说Java面试题】【Java基础篇】第30题:JDK动态代理和CGLIB动态代理有什么区别
java·开发语言·后端·面试·代理模式
DFT计算杂谈12 小时前
wannier90 参数详解大全
java·前端·css·html·css3