mybatis plus 批量插入回填自增ID
时间: 2025-02-23 20:25:21 浏览: 75
### 使用 MyBatis Plus 批量插入并回填自增 ID
#### 配置 `useGeneratedKeys` 和 `keyProperty`
为了使 MyBatis Plus 支持批量插入时回填自增 ID,在 XML 映射文件中的 SQL 插入语句需指定两个重要属性:`useGeneratedKeys="true"` 以及 `keyProperty="id"`。前者告知 JDBC 获取数据库生成的主键,后者则指明实体类中用于存储此主键值的字段名称[^3]。
```xml
<insert id="batchInsertWithIdBackfill" useGeneratedKeys="true" keyProperty="id">
INSERT INTO table_name (column1, column2,...)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.column1}, #{item.column2},...)
</foreach>
</insert>
```
上述代码片段展示了如何定义一个可以接受列表参数并通过循环结构来构建多个值集的方法,从而完成一次性的多条记录插入操作的同时确保每个新创建的对象都能获得其对应的唯一标识符[^1]。
#### Java 代码示例
在服务层编写相应的业务逻辑处理函数:
```java
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
@Service
public class YourServiceImpl extends ServiceImpl<YourMapper, YourEntity> {
public boolean batchSave(List<YourEntity> entities){
try {
saveBatch(entities);
return true;
} catch (Exception e) {
log.error("Failed to perform batch insertion with id backfill", e);
return false;
}
}
}
```
这里调用了来自父类 `ServiceImpl` 提供的一个便捷方法 `saveBatch()` 来执行实际的数据保存动作,并且自动实现了对传入集合内每一个实例对象的主键赋值过程[^4]。
阅读全文
相关推荐





