可以使用 MybatisPlus 的 KeyGenerator 来解决 ID 不回显的问题。具体的步骤如下:

  1. 在实体类中添加 @Id 注解,指定主键生成策略。
@Data
public class User {
    @Id
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
}
  1. 在 Mapper 接口中添加 @MapperScan 注解,指定 Mapper 的包路径。
@MapperScan("com.example.mapper")
public interface UserMapper extends BaseMapper<User> {} 
  1. 创建一个自定义的 KeyGenerator,继承自 MybatisPlus 的 AbstractKeyGenerator 抽象类,并实现其 generateKey 方法。
public class CustomKeyGenerator extends AbstractKeyGenerator {
    @Override
    protected String getSeqName() {
        return "SEQ_USER_ID";
    }

    @Override
    public synchronized Number generateKey() {
        return super.generateKey();
    }
}
  1. 在 Mapper 接口中添加 @KeySequence 注解,指定自定义的 KeyGenerator。
@Mapper
@KeySequence("SEQ_USER_ID")
public interface UserMapper extends BaseMapper<User> {} 
  1. 在配置文件中添加自定义的 KeyGenerator。
<bean id="customKeyGenerator" class="com.example.CustomKeyGenerator"/>
  1. 在 MybatisPlus 的配置文件中配置自定义的 KeyGenerator。
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
    <property name="dbConfig" ref="dbConfig"/>
    <property name="metaObjectHandler" ref="metaObjectHandler"/>
    <property name="keyGenerator" ref="customKeyGenerator"/>
</bean>
  1. 在代码中使用 MybatisPlus 的批量插入方法。
List<User> userList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
    User user = new User();
    user.setName("user" + i);
    user.setAge(i);
    userList.add(user);
}
userMapper.insertBatchSomeColumn(userList);
MybatisPlus 批量插入 ID 不回显问题解决方案

原文地址: https://www.cveoy.top/t/topic/oBW8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录