mybatis 批量插入
时间: 2023-10-15 15:05:16 浏览: 166
可以使用 MyBatis 的批量插入功能来一次插入多条数据,可以大大提高插入效率。具体实现方式可以在 Mapper.xml 文件中使用 insert 标签,并在 insert 标签中添加 foreach 循环语句来进行批量插入。以下是一个示例:
```
<insert id="batchInsert" parameterType="java.util.List">
insert into user (id, name, age) values
<foreach collection="list" item="item" separator=",">
(#{item.id}, #{item.name}, #{item.age})
</foreach>
</insert>
```
其中,#{item.id}、#{item.name}、#{item.age} 是对应一条记录中的 id、name、age 字段的值。在使用时,需要将多条记录封装成一个 List 对象传入该方法即可。
相关问题
MyBatis批量插入
### MyBatis 批量插入实现方式
#### 使用 `<foreach>` 标签进行批量插入
在 MyBatis 中,`<foreach>` 标签用于遍历集合并构建 SQL 语句。这种方式适用于大多数场景下的批量插入操作。
```xml
<insert id="batchInsert">
INSERT INTO users (username, password)
VALUES
<foreach collection="list" item="item" index="index" open="" separator="," close="">
(#{item.username}, #{item.password})
</foreach>
</insert>
```
此方法允许将多个值组合成单个 SQL 插入语句[^1]。
#### 设置 `ExecutorType.BATCH` 进行批量处理
另一种高效的方法是设置执行器类型为 `Batch`,这可以在一定程度上减少与数据库之间的交互次数,从而提升性能:
```java
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
for (User user : userList) {
mapper.insert(user);
}
sqlSession.commit();
} finally {
sqlSession.close();
}
```
当使用 `ExecutorType.BATCH` 时,所有的更新命令会被缓存起来直到调用了 commit 或者 flushStatements() 方法才会真正发送到数据库服务器[^3]。
#### 自定义批量插入逻辑
对于更复杂的业务需求,还可以考虑编写自定义的批量插入逻辑来优化特定情况下的性能表现。例如分批次提交数据以避免内存溢出等问题。
```java
public void customBatchInsert(List<User> users){
int batchSize = 1000;
SqlSession sqlSession = null;
try{
sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
for(int i=0;i<users.size();i++){
mapper.insert(users.get(i));
if((i+1)%batchSize==0 || (i+1)==users.size()){
sqlSession.flushStatements();
sqlSession.clearCache();
}
}
sqlSession.commit();
}catch(Exception e){
if(sqlSession!=null){
sqlSession.rollback();
}
throw new RuntimeException(e.getMessage(),e);
}finally{
if(sqlSession != null){
sqlSession.close();
}
}
}
```
这种方法能够更好地控制每次向数据库传输的数据量大小,适合处理非常大规模的数据集[^4]。
Mybatis 批量插入
Mybatis 批量插入有两种方式可选。第一种方式是拼接批量插入多条数据的SQL,通过在mapper接口中定义一个insertDataList方法,参数为数据列表,然后在XML文件中配置对应的SQL语句,使用foreach循环将数据列表中的数据插入到数据库中。\[2\]第二种方式是使用Batch Insert技术,通过在应用层代码中使用SqlSession的BATCH执行器类型,然后在循环中调用insertMapper的insertData方法将数据逐条插入到数据库中,最后通过session.commit()提交事务。\[1\]这两种方式都可以提升数据持久化的性能,适用于需要批量插入大量数据的场景,比如从离线文件导入数据、定时或人工同步数据以及程序自身生成大批量数据保存到数据库的情况。\[3\]
#### 引用[.reference_title]
- *1* *2* *3* [Mybatis批量插入数据的两种方式](https://blog.csdn.net/ylforever/article/details/126592028)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文
相关推荐
















