mybatis-plus 根据数据库主键定义字段类型

查看mybatis-plus源代码IdType

package com.baomidou.mybatisplus.annotation;

public enum IdType {
  AUTO(0),            //数据库自增 依赖数据库
  NONE(1),            //表示该类型未甚至主键类型 (如果没有主键策略)默认根据雪花算法生成
  INPUT(2),           //用户输入ID(该类型可以通过自己注册填充插件进行填充)
  //下面这三种类型,只有当插入对象id为空时 才会自动填充
  ID_WORKER(3),       //全局唯一(idWorker)数值类型
  UUID(4),            //全局唯一(UUID)
  ID_WORKER_STR(5);   //全局唯一(idWorker的字符串表示)

  private int key;

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

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

在实体类中ID属性字段加注解

@TableId(type = IdType.AUTO) 主键自增 数据库中需要设置主键自增
private Long id;
@TableId(type = IdType.NONE) 默认 跟随全局策略走
private Long id;
@TableId(type = IdType.UUID) UUID类型主键
private Long id;
@TableId(type = IdType.ID_WORKER) 数值类型  数据库中也必须是数值类型 否则会报错
private Long id;
@TableId(type = IdType.ID_WORKER_STR) 字符串类型   数据库也要保证一样字符类型
private Long id;
@TableId(type = IdType.INPUT) 用户自定义了  数据类型和数据库保持一致就行
private Long id;

全局主键策略实现

在application.yml文件中进行全局设置

 

mybatis-plus:
  mapper-locations:
    - com/mp/mapper/*
  global-config:
    db-config:
      id-type: uuid/none/input/id_worker/id_worker_str/auto   表示全局主键都采用该策略(如果全局策略和局部策略都有设置,局部策略优先级高)

 

你可以使用MyBatis-Plus的`insert`方法来实现新增SQL主键自增,并将新增的主键复制到其他字段。 首先,确保你的实体类中的主键字段使用了`@TableId`注解,并且设置了主键生成策略为自增。例如: ```java import com.baomidou.mybatisplus.annotation.TableId; public class User { @TableId(type = IdType.AUTO) private Long id; private String name; // 其他字段... // 省略getter和setter方法 } ``` 接下来,使用MyBatis-Plus的`insert`方法插入数据,并在插入后获取到新增的主键值。然后,将该主键值赋给其他字段。示例如下: ```java import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import org.springframework.beans.factory.annotation.Autowired; public class UserService { @Autowired private BaseMapper<User> userMapper; public void insertUser(User user) { userMapper.insert(user); // 获取新增的主键值 Long primaryKey = user.getId(); // 将主键值赋给其他字段 userMapper.update(user, new UpdateWrapper<User>() .eq("id", primaryKey) .set("other_column", primaryKey) ); } } ``` 在上述示例中,我们在插入数据后使用了`update`方法来更新其他字段,将新增的主键值赋给了`other_column`字段。你可以根据实际需求调整相关代码。 希望这可以帮助到你!如果你还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值