杂记:myBatis-plus中修改主键填充策略

myBatis-plus中主键id默认使用雪花算法生成的唯一id,当我们实际业务中需要自定义时,可以修改其填充策略,符合项目要求。
1,局部主键策略实现

在实体类中 ID属性加注解

@TableId(type = IdType.AUTO) 主键自增 数据库中需要设置主键自增
private Long id;
@TableId(type = IdType.NONE) 默认 跟随全局策略走
private Long id;
@TableId(type = IdType.UUID) UUID类型主键
private Long id;
@TableId(type = IdType.ID_WORKER) 数值类型 数据库中也必须是数值类型 否则会报错
private Long id;
@TableId(type = IdType.ID_WORKER_STR) 字符串类型 数据库也要保证一样字符类型
private Long id;
@TableId(type = IdType.INPUT) 用户自定义了 数据类型和数据库保持一致就行
private Long id;

2,全局主键策略实现

需要在application.yml文件中

添加

mybatis-plus:
mapper-locations:
- com/mp/mapper/*
global-config:
db-config:
id-type: uuid/none/input/id_worker/id_worker_str/auto 表示全局主键都采用该策略(如果全局策略和局部策略都有设置,局部策略优先级高)

源码:
/*

  • Copyright © 2011-2020, baomidou (jobob@qq.com).
  • Licensed under the Apache License, Version 2.0 (the “License”); you may not
  • use this file except in compliance with the License. You may obtain a copy of
  • the License at
  • https://www.apache.org/licenses/LICENSE-2.0
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
  • WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  • License for the specific language governing permissions and limitations under
  • the License.
    */
    package com.baomidou.mybatisplus.annotation;

import lombok.Getter;

/**

  • 生成ID类型枚举类

  • @author hubin

  • @since 2015-11-10
    /
    @Getter
    public enum IdType {
    /
    *

    • 数据库ID自增
      /
      AUTO(0),
      /
      *
    • 该类型为未设置主键类型
      /
      NONE(1),
      /
      *
    • 用户输入ID
    • 该类型可以通过自己注册自动填充插件进行填充

    */
    INPUT(2),

    /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 /
    /
    *

    • 全局唯一ID (idWorker)
      /
      ID_WORKER(3),
      /
      *
    • 全局唯一ID (UUID)
      /
      UUID(4),
      /
      *
    • 字符串全局唯一ID (idWorker 的字符串表示)
      */
      ID_WORKER_STR(5);

    private final int key;

    IdType(int key) {
    this.key = key;
    }
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值