Mybatis-plus obtains the ID generated by the snowflake algorithm in advance and returns the generated ID


1. MybatisPlus primary key strategy

  • AUTO: Use the database id auto-increment strategy to control id generation;
  • NONE: Do not set the id generation strategy;
  • INPUT: The user manually enters the id;
  • ASSIGN_ID: ID generated by snowflake algorithm (compatible with numeric and string types);
  • ASSIGN_UUID: Use UUID generation algorithm as id generation strategy;

(1) The default primary key strategy of Mybatis is @TableId(type = IdType.ASSIGN_ID). This is the default strategy snowflake algorithm. At this time, the primary key type can be String or the data type bigint. There is no need to increment the primary key of the data table; (2)
@TableId (type = IdType.ASSIGN_AUTO) is the primary key auto-increment strategy. This strategy follows the primary key increment strategy of the database table. The premise is that the primary key of the database table must be set to auto-increment. Therefore, if the primary key field of the data table needs to auto-increment, generally choose int bigint;
(3) @TableId(type = IdType.INPUT) This strategy means that we must manually insert the id, otherwise we cannot add data, so we need to auto-increment the primary key of the data table and remove it; (4) @TableId(type =
IdType.NONE )NONE strategy means not specifying a primary key generation strategy. When we do not specify a primary key generation strategy or the primary key strategy is NONE, the global strategy follows. Therefore, even if @TableId does not specify a primary key strategy, the snowflake algorithm is used.

2. Mybatis-plus obtains the ID generated by the snowflake algorithm for entity classes in advance

  In some cases, we want to get this ID in advance so that we can generate the values ​​of other fields through some calculations. Because Mybatis-plus has a built-in snowflake algorithm generation function, we can just find it and call it. There is no need to manually go through the algorithm at all.
  The algorithm is specifically implemented in the following class, so I won’t post the code in a large area.

import com.baomidou.mybatisplus.core.toolkit.IdWorker;

We can call it like this, where entity is the object we want to persist.

Long ID=IdWorker.getId(entity);

注意:拿到ID之后,需要手动将ID赋值到entity对象上;如果不手动赋值,执行完save()方法之后,又会重新生成一个ID,就跟上面方法取到的ID不一致了。

  If you have more special needs, you can also set other parameters of the snowflake algorithm. The source code of this class is as follows. The comments in it are more detailed. I hope it can help you.

package com.baomidou.mybatisplus.core.toolkit;
 
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
 
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
 
/**
 * id 获取器
 *
 */
public class IdWorker {
    
    
 
    /**
     * 主机和进程的机器码
     */
    private static IdentifierGenerator IDENTIFIER_GENERATOR = new DefaultIdentifierGenerator();
 
    /**
     * 毫秒格式化时间
     */
    public static final DateTimeFormatter MILLISECOND = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
 
    /**
     * 获取唯一ID
     *
     * @return id
     */
    public static long getId() {
    
    
        return getId(new Object());
    }
 
    /**
     * 获取唯一ID
     *
     * @return id
     */
    public static long getId(Object entity) {
    
    
        return IDENTIFIER_GENERATOR.nextId(entity).longValue();
    }
 
    /**
     * 获取唯一ID
     *
     * @return id
     */
    public static String getIdStr() {
    
    
        return getIdStr(new Object());
    }
 
    /**
     * 获取唯一ID
     *
     * @return id
     */
    public static String getIdStr(Object entity) {
    
    
        return IDENTIFIER_GENERATOR.nextId(entity).toString();
    }
 
    /**
     * 格式化的毫秒时间
     */
    public static String getMillisecond() {
    
    
        return LocalDateTime.now().format(MILLISECOND);
    }
 
    /**
     * 时间 ID = Time + ID
     * <p>例如:可用于商品订单 ID</p>
     */
    public static String getTimeId() {
    
    
        return getMillisecond() + getIdStr();
    }
 
    /**
     * 有参构造器
     *
     * @param workerId     工作机器 ID
     * @param dataCenterId 序列号
     * @see #setIdentifierGenerator(IdentifierGenerator)
     */
    public static void initSequence(long workerId, long dataCenterId) {
    
    
        IDENTIFIER_GENERATOR = new DefaultIdentifierGenerator(workerId, dataCenterId);
    }
 
    /**
     * 自定义id 生成方式
     *
     * @param identifierGenerator id 生成器
     * @see GlobalConfig#setIdentifierGenerator(IdentifierGenerator)
     */
    public static void setIdentifierGenerator(IdentifierGenerator identifierGenerator) {
    
    
        IDENTIFIER_GENERATOR = identifierGenerator;
    }
 
    /**
     * 使用ThreadLocalRandom获取UUID获取更优的效果 去掉"-"
     */
    public static String get32UUID() {
    
    
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return new UUID(random.nextLong(), random.nextLong()).toString().replace(StringPool.DASH, StringPool.EMPTY);
    }
}

3. MybatisPlus adds a new object and returns the generated ID

  Through the introduction in Chapter 2, you must have noticed that after executing the save() method, the MybatisPlus framework actually helps us create IDs, assign them to entity objects, and then persist the objects with IDs. , so it is easier to get the generated ID at this time. The reference code is as follows:

The save() method is encapsulated in advance by MybatisPlus and can be called directly.

save(entity);
System.out.println(entity.getId());    //保存完之后,直接可以获取到生成的ID

Isn't it very simple? I also stepped on a lot of pitfalls at the beginning. I referred to other people's posts and modified the Mapper and the service. I could implement some operation functions, but the code was not elegant at all. I couldn't bear it and thought about it. MybatisPlus is so awesome, how could it not have this function? So after carefully studying MybatisPlus, I successfully got out of the pit.

(Finish)

Guess you like

Origin blog.csdn.net/bacawa/article/details/131686367