MyBatis 您所在的位置:网站首页 雪花算法生成id的长度 MyBatis

MyBatis

2024-07-14 16:24| 来源: 网络整理| 查看: 265

MyBatis-Plus主键策略(雪花算法16位长度的整型id,解决默认雪花算法生成19位长度id导致JS精度丢失问题)

js表达的最大整数2的53次方减1,精度丢失后面几位全是0!

主键策略

如果内置支持不满足你的需求,可实现 IKeyGenerator 接口来进行扩展.

举个栗子

@KeySequence(value = "SEQ_ORACLE_STRING_KEY", clazz = String.class) public class YourEntity { @TableId(value = "ID_STR", type = IdType.INPUT) private String idStr; }

#Spring-Boot #方式一:使用配置类 @Bean public IKeyGenerator keyGenerator() { return new H2KeyGenerator(); }

#方式二:通过 MybatisPlusPropertiesCustomizer 自定义 @Bean public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() { return plusProperties -> plusProperties.getGlobalConfig().getDbConfig().setKeyGenerator(new H2KeyGenerator()); }

#Spring #方式一: XML 配置

#方式二:注解配置 @Bean public GlobalConfig globalConfig() { GlobalConfig conf = new GlobalConfig(); conf.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerator(new H2KeyGenerator())); return conf; }

官方示例

官方id generator示例https://gitee.com/baomidou/mybatis-plus-samples/tree/master/mybatis-plus-sample-id-generator

工程中16位长度的long整型id示例 @Component public class CustomerIdGenerator implements IdentifierGenerator { @Override public Long nextId(Object entity) { // 填充自己的Id生成器, return IdGenerator.generateId(); } }

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


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有