MybatisPlus 批量插入 ID 不回显问题解决方案
可以使用 MybatisPlus 的 KeyGenerator 来解决 ID 不回显的问题。具体的步骤如下:
- 在实体类中添加
@Id注解,指定主键生成策略。
@Data
public class User {
@Id
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
}
- 在 Mapper 接口中添加
@MapperScan注解,指定 Mapper 的包路径。
@MapperScan("com.example.mapper")
public interface UserMapper extends BaseMapper<User> {}
- 创建一个自定义的 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();
}
}
- 在 Mapper 接口中添加
@KeySequence注解,指定自定义的 KeyGenerator。
@Mapper
@KeySequence("SEQ_USER_ID")
public interface UserMapper extends BaseMapper<User> {}
- 在配置文件中添加自定义的 KeyGenerator。
<bean id="customKeyGenerator" class="com.example.CustomKeyGenerator"/>
- 在 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>
- 在代码中使用 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);
原文地址: https://www.cveoy.top/t/topic/oBW8 著作权归作者所有。请勿转载和采集!