mybatis-plus主键生成策略

mybatis-plus主键生成策略

MP 支持多种主键策略 默认是推特的“” 雪花算法“” ,也可以设置其他策略,主键策略使用

MP的主键定义在一个一个枚举类中 源码如下

public enum IdType {
  AUTO(0),//数据库自增 依赖数据库
  NONE(1),// 表示该类型未甚至主键类型 (如果没有主键策略)默认根据雪花算法生成
  INPUT(2),//用户输入ID(该类型可以通过自己注册填充插件进行填充)
  //下面这三种类型,只有当插入对象id为空时 才会自动填充。
  ID_WORKER(3),//全局唯一(idWorker)数值类型
  UUID(4),//全局唯一(UUID)
  ID_WORKER_STR(5);//全局唯一(idWorker的字符串表示)

  private final int key;

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

  public int getKey() {
    return this.key;
  }
}


局部主键策略实现

在实体类中 ID属性加注解

/*
 * Copyright (c) 2011-2021, 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
 *
 *     http://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自增
     * <p>该类型请确保数据库设置了 ID自增 否则无效</p>
     */
    AUTO(0),
    /**
     * 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
     */
    NONE(1),
    /**
     * 用户输入ID
     * <p>该类型可以通过自己注册自动填充插件进行填充</p>
     */
    INPUT(2),

    /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
    /**
     * 分配ID (主键类型为number或string),
     * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(雪花算法)
     *
     * @since 3.3.0
     */
    ASSIGN_ID(3),
    /**
     * 分配UUID (主键类型为 string)
     * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(UUID.replace("-",""))
     */
    ASSIGN_UUID(4),
    /**
     * @deprecated 3.3.0 please use {@link #ASSIGN_ID}
     */
    @Deprecated
    ID_WORKER(3),
    /**
     * @deprecated 3.3.0 please use {@link #ASSIGN_ID}
     */
    @Deprecated
    ID_WORKER_STR(3),
    /**
     * @deprecated 3.3.0 please use {@link #ASSIGN_UUID}
     */
    @Deprecated
    UUID(4);

    private final int key;

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


全局主键策略实现

需要在application.yml文件中

添加

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

自定义主键生成策略

CustomIdGenerator继承IdentifierGenerator接口

代码如下:

package com.liu.news.artical;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.liu.news.utils.IdGeneratorSnowflake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author lx
 * @version 1.0
 * @description: TODO
 * @date 2021/8/4 11:11
 */
@Slf4j
@Component
public class CustomIdGenerator implements IdentifierGenerator {

    private final AtomicLong al = new AtomicLong(1111015);
    @Autowired
    private IdGeneratorSnowflake idGenerator;

    @Override
    public Long nextId(Object entity) {
        //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
       // String bizKey = entity.getClass().getName();
        //log.info("bizKey:{}", bizKey);
       // MetaObject metaObject = SystemMetaObject.forObject(entity);
        //final long id = al.getAndAdd(121);
        final long id = idGenerator.snowflakeId(0,0);
        log.info("为{}生成主键值->:{}",id);
        return id;
    }
}

 //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
       // String bizKey = entity.getClass().getName();
        //log.info("bizKey:{}", bizKey);
       // MetaObject metaObject = SystemMetaObject.forObject(entity);
        //final long id = al.getAndAdd(121);自定义的主键策略

idGenerator.snowflakeId(0,0); 雪花算法

package com.liu.news.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author lx
 * @version 1.0
 * @description: TODO
 * @date 2021/8/4 11:26
 */
@Component
public class IdGeneratorSnowflake {
    private long workerId = 0;
    private long datacenterId = 1;
    private Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);

    private static final Logger log = LoggerFactory.getLogger(IdGeneratorSnowflake.class.getName());

    // 依赖注入完成后执行该方法,进行一些初始化工作
    @PostConstruct
    public void init() {
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器的workerId: {}", workerId);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("当前机器的workerId获取失败", e);
            // 释放ID
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    // 使用默认机房号获取ID
    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    // 自己制定机房号获取ID
    public synchronized long snowflakeId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);

        return snowflake.nextId();
    }

    /**
     * 生成的是不带-的字符审,类似于: 73a64edf935d4952a287739a66f96e06
     *
     * @return
     */
    public String simpleUUID() {
        return IdUtil.simpleUUID();
    }

    /**
     * 生成的UUID是带-的字符串,类似于: b12b6401-6f9c-4351-b2b6-d8afc9ab9272
     *
     * @return
     */
    public String randomUUID() {
        return IdUtil.randomUUID();
    }

    public static void main(String[] args) {
        IdGeneratorSnowflake f = new IdGeneratorSnowflake();
        for (int i = 0; i < 1000; i++) {

            System.out.println(f.snowflakeId(0, 0));
        }

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值