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

被折叠的 条评论
为什么被折叠?



