boot 中 Mybatis plus 自定义String类型的主键id并且自动填充

boot 中 Mybatis plus 自定义String类型的主键id自动填充

问题描述

数据库设置时,需要生成的id时表名字 + 时间+ 随机数的格式,类型是String。

解决分析

这里用的mybatis plus 去实现的,官方有给出方案,但是,没有详细说明,而且只给出了返回Long类型的!

问题解决

首先这里使用的版本是3.3.2的版本
官方指出,要去重写这个接口,冷眼一看,必然是重写nextId() 方法,这样做是对的,但是这个只能生成Number类型的!

仔细看了之后,发现有个默认实现default String nextUUID(),我们需要的,正是这个。

public interface IdentifierGenerator {
    Number nextId(Object entity);
    // 这里是重点
    default String nextUUID(Object entity) {
        return IdWorker.get32UUID();
    }
}

代码

/**
 * 自定义ID生成器
 *
 * @author sxd
 */
@Slf4j
@Component
public class CustomIdGenerator implements IdentifierGenerator {

    private final AtomicLong al = new AtomicLong(1);

    public Long nextId(Object entity) {
        return null;
    }

    /**
     * String 类型id生成
     *
     * @param entity
     * @return
     */
    public String nextUUID(Object entity) {
        // 下面是我的生成逻辑,我是获取表首字母缩写 + 时间 + 随机数
        String getSimpleName = entity.getClass().getSimpleName();
        String threeLetter = IdUtil.getThreeLetter(getSimpleName);
        if (threeLetter == null){
            threeLetter = getThreeLetter(getSimpleName);
        }
        return U_sql.generateId(threeLetter);
    }

只做这些还是不够的,需要改yml配置文件中的idtype

mybatis-plus:
  global-config:
    db-config:
      id-type: ASSIGN_UUID

按照这里的配置,就可以实现了

参考官网指南
参考官网配置

猜你喜欢

转载自blog.csdn.net/weixin_43141746/article/details/107326284
今日推荐