MyBatis Batch Update Exception 使用foreach 批量update 出错

本文讨论了在使用MyBatis进行批量更新操作时遇到的问题,特别是当数据库连接字符串默认不支持一次性执行多个SQL语句时。通过在配置中添加参数allowMultiQueries并设置为true,成功解决了批量更新操作执行失败的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源地址   http://quabr.com/22829539/mybatis-batch-update-exception


使用如下Mybatis  map xml文件 

<update id="updateTestcaseNodeBatch" parameterType="List">
  <foreach collection="list" item="nodeVO" separator=";">
    UPDATE testcase_node
     <set>
       name=#{nodeVO.name},
       version=#{nodeVO.version},
       description=#{nodeVO.description},
       last_modify_user=#{nodeVO.createUser},
       last_modify_time=#{nodeVO.createTime}
     </set>
     <where>
       object_id=#{nodeVO.objectId} AND root_id=#{nodeVO.rootId}
     </where>
  </foreach>
</update>

出错信息:

### The error may involve com.hirain.testmanagement.mapper.TestcaseNodeMapper.updateTestcaseNodeBatch-Inline
### The error occurred while setting parameters
### SQL: UPDATE testcase_node       SET name=?,        version=?,        description=?,        last_modify_user=?,        last_modify_time=?        WHERE object_id=? AND root_id=?     ;      UPDATE testcase_node       SET name=?,        version=?,        description=?,        last_modify_user=?,        last_modify_time=?        WHERE object_id=? AND root_id=?
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; 
    UPDATE testcase_node
      SET name='Türstatus',
       version=4,
     ' at line 8
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; 
    UPDATE testcase_node
      SET name='Türstatus',
       version=4,
     ' at line 8
    at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:233)


仔细检查 map文件 和数据库表字段没有错误

最终结果是因为 配置的 mysql jdbc 链接字符串 默认不支持一次性执行多个sql 语句;

但是在我们的 update map中需要执行多个 update语句。

最后加上参数 "allowMultiQueries" 设置为true  如下:

<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;allowMultiQueries=true" />  


问题解决!


### 使用 MyBatis 进行批量更新 MyBatis 支持多种方式来执行批量更新操作,这有助于优化数据库交互并减少应用程序与数据库之间的数据传输量[^1]。 #### 方法一:使用 `foreach` 标签实现批量更新 通过 XML 映射文件中的 `<update>` 和 `<foreach>` 标签组合可以轻松完成批量更新。这种方式允许开发者自定义 SQL 语句,并能有效地处理多个记录的同时更新。 ```xml <update id="batchUpdateUsers" parameterType="java.util.List"> UPDATE users SET name=#{item.name}, email=#{item.email} WHERE user_id=#{item.userId} <foreach collection="list" item="item" separator=";"> <!-- Each iteration will generate an individual update statement --> </foreach> </update> ``` 此方法利用分号(`;`)作为每条独立更新命令间的分隔符,在某些情况下可能需要调整 JDBC 驱动程序设置以支持多条语句的执行。 #### 方法二:启用批处理模式 为了进一步提高性能,可以在会话级别开启批处理功能。当启用了批处理之后,所有的插入、更新以及删除操作都会被缓存起来直到调用 `flushStatements()` 或者关闭 session 的时候才会真正提交给数据库服务器。 ```java try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); for (User user : userList) { mapper.updateUser(user); // This won't be sent immediately but cached instead. } sqlSession.flushStatements(); // Send all updates at once after processing entire list. } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } ``` 这种方法不仅提高了效率还减少了网络往返次数,对于大规模的数据集尤其有效。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值