不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2022-05-15 18:18:18  修改时间:2024-04-28 23:19:55  分类:Java框架/系统  编辑

1. 概述

MyBatis-Plus为我们支持了许多种的主键策略,主键策略是指MyBatis-Plus可以自动生成主键的策略,不需要手动插入主键,MyBatis-Plus的主键策略帮我们自动生成主键

2.官方网站

主键策略 | MyBatis-Plus

3.主键策略

public enum IdType {
	/**
	 * 数据库自增
	 * 注:需设置数据库自增
	 */
	AUTO(0),
	/**
	 * 不设置任何策略,但是会跟随全局策略
	 */
	NONE(1),
	/**
	 * 手动输入
	 */
	INPUT(2),
	/**
	 * 使用雪花算法生成主键
	 */
	ASSIGN_ID(3),
	/**
	 * 使用UUID生成主键
	 */
	ASSIGN_UUID(4);

	private final int key;

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

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

4.实例

在字段上面加上注解即可使用MyBatis-Plus的主键策略

@Data
public class User {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

5.自定义主键策略实现

通过实现IdentifierGenerator接口,撰写自定义id策略

/**
 * 自定义ID生成器,仅作为示范
 */
@Slf4j
@Component
public class CustomIdGenerator implements IdentifierGenerator {
 
    private final AtomicLong al = new AtomicLong(1);
 
    @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;
    }
}

6.全局主键策略实现

6.1 导入依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>MyBatis-Plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

6.2 在yml文件中设置全局主键策略

注:我在此使用的是雪花算法的主键策略

server:
  port: 1000
spring:
  application:
    name: tanhua-usercenter
 
  main:
    allow-bean-definition-overriding: true
#redis
  redis:
    host: 192.168.56.10
    port: 6379
#全局时间策略
  jackson:
    time-zone: GMT+8
    default-property-inclusion: always
    date-format: yyyy-MM-dd HH:mm:ss
#全局主键策略:雪花算法主键策略
MyBatis-Plus:
  global-config:
    db-config:
      id-type: ASSIGN_ID

6.3 在实体类中使用注解

在主键上添加注解@TableId(type= IdType.NONE),定义了全局策略如果要使用全局策略必须使用IdType.NONE,这种表示不设置任何策略,但是如果设置了全局策略,则会跟随全局策略,如果设定其他主键策略的情况,会优先使用当前设置的主键策略。

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo extends BasePojo implements Serializable{
 
    /**
     * 由于userinfo表和user表之间是一对一关系
     *   userInfo的id来源于user表的id
     */
    @ApiModelProperty(value = "主键")
    @TableId(type= IdType.NONE)
    private Long id; //用户id
 
    @ApiModelProperty(value = "昵称")
    @TableField("mobile")
    private String mobile; //昵称
 
    @ApiModelProperty(value = "用户头像")
    @TableField("avatar")
    private String avatar; //用户头像
}