SpringBoot整合MP(MybatisPlus)自定义ID生成器

本文介绍了如何在Mybatis Plus中实现自定义ID生成器,通过编写实现IdentifierGenerator接口的类并重写nextId和nextUUID方法。示例代码展示了如何使用AtomicLong生成递增ID,并利用UUIDUtil生成无中划线的UUID。该类可用于根据业务需求生成不同类型的唯一标识。

自定义ID生成器是mp的核心功能。默认使用雪花算法+UUID(不含中划线)

如果需要自定义的话,我们需要2个步骤。

1、写个类去实现 IdentifierGenerator 。

2、重写nextUUID或nextId

 @Override
 public String nextUUID  (Object entity) {
 public Long   nextId(Object entity) {

 

完整代码:

package org.example;

import java.util.concurrent.atomic.AtomicLong;

import com.power.common.util.UUIDUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义ID生成器
 * 仅作为示范
 *
 * @author nieqiuqiu 2019/11/30
 */
@Slf4j
@Component
public class CustomIdGenerator implements IdentifierGenerator {

    private final AtomicLong al = new AtomicLong(8);

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

    @Override
    public String nextUUID  (Object entity) {
        //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.

        log.info("为{}生成主键值->:{}", "name", "id");
        return UUIDUtil.getUuid();
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东宇科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值