您的位置:首页 > 其它

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

2020-02-04 00:20 197 查看

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;
}
}

  • 点赞
  • 收藏
  • 分享
  • 文章举报
白衣渡江-吕子明 发布了5 篇原创文章 · 获赞 0 · 访问量 115 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: