6

MybatisPlus生成主键策略方法 - 面向CV工程师

 1 year ago
source link: https://www.cnblogs.com/b10100912/p/16796560.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

MybatisPlus生成主键策略方法

全局id生成策略【因为是全局id所以不推荐】

SpringBoot集成Mybatis-Plus

在yaml配置文件中添加MP配置

mybatis-plus: global-config: db-config: #主键类型(auto:"自增id",assign_id:"全局唯一id(雪花算法,Long或者String类型)", assign_uuid:"全局唯一id(无中划线的uuid)",input:"自行设置id,默认null",none:"不设置主键id") id-type: assign_id

局部id生成策略【局部id非常推荐】

在实体类当中使用@TableId注解配置id生成类型

@TableId(type = IdType.AUTO)private String id;

注意事项:

  • 同时配置了这两种策略时,局部字段的ID生成策略优先级高于全局的id生成策略

  • 使用雪花算法生成ID后,再次切换为主键自增的ID生成策略后会导致起始序列过大(没有重置起始序列值)

  • 另外如果原先指定了@TableId(type = IdType.AUTO),然后去除这部分代码,会发生Tuncate操作(即清空表并重置ID起始值)

如果大家没有用到MybaitsPlus,也可以用java自带的生成方法

因为一般数据库主键为String类型,所以接收类型为String,生成的uuid数据包含-,所以要去掉-,

java.util.UUID.randomUUID().toString().replace("-", "").toLowerCase();

也可以用hutool中的生成方法,下面是以int类型为例子

int context = Math.abs(IdUtil.fastSimpleUUID().hashCode());

也可以用当前时间戳+随机id的形式生成唯一的,下面是以String类型为例子,
(当并发创建时有可能会重复所以建议使用雪花算法)

Date date = new Date();String context = DateUtil.format(date,"yyyyMMdd") +Math.abs(IdUtil.fastSimpleUUID().hashCode());

使用hutool需要导入依赖

<!-- Hutool--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version> </dependency>

当然这些只是我的建议,大家可以去找找其他的方法。
有知道其他方法的小伙伴们欢迎在底下留言,本人小白一枚轻喷!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK