解决mybatis批量更新(update foreach)失败的问题
如下所示:
<!--批量更新报表 --> <update id="updateIssueByBatch" parameterType="java.util.List"> <foreach collection="issueList" item="item" index="index" separator=";"> update sys_issue <set> <if test="item.first != null and item.first != ''">first_class = #{item.first}, </if> <if test="item.second != null and item.second != ''">second_class = #{item.second}, </if> updated_time = now() </set> where id = #{item.Id} </foreach> </update>
报错如下:
The error occurred while setting parameters
问题描述:
上网查询说是 配置mysql的时候没有开启批量插入,就查询了项目 是否 配置了 allowMultiQueries=true ,发现本地和线上都配置了该语句,问题没出在这。那么问题出在哪呢?后来发现是由于线上将 & 变成了 & 造成的。
* 前后对比如下:*
修改前:
jdbc.url=jdbc:mysql://XXX/abc?useUnicode=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
修改后:
jdbc.url=jdbc:mysql://XXX/abc?useUnicode=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
补充知识:Mybatis 批量更新失败,单条成功
在项目开发过程中,结合业务场景,需要对某个表进行批量更新,完成所有的业务代码和Mybatis XML文件后,单元测试时,发现调用批量更新只有一条记录时,执行成功,传入多条记录,进行批量更新时,则提示失败,错误信息如下:
org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. 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 '...... ### The error may involve .... ### The error occurred while setting parameters ### SQL:
其中XML映射批量更新的结构如下:
<!-- 批量更新 --> <update id="batchUpdate" parameterType="java.util.List"> <foreach collection="list" item="item" separator=";"> update xxxxxx <set> <if test="item.xxx!= null"> xxx= #{item.xxx,jdbcType=BIGINT}, </if> ...... </set> where id =#{item.id} </foreach> </update>
经过代码排查,以及批量update语句通过SQL工具直接执行均能成功,排除代码和sql语句问题,最后求助Google大神,发现使用mybatis进行批量插入与更新时,必须在配置连接url时指定allowMultiQueries=true
mysql.db.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&&allowMultiQueries=true
经测试,完美解决此问题。
以上这篇解决mybatis批量更新(update foreach)失败的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
springboot中报错Invalid character found in
这篇文章主要介绍了springboot中报错Invalid character found in the request的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-09-09详解JavaEE使用过滤器实现登录(用户自动登录 安全登录 取消自动登录黑用户禁止登录)
主要介绍用户的自动登录和取消自动登录,以及实现一天自动登录或者n天实现自动登录,当用户ip被加入到黑名单之后,直接利用过滤器返回一个警告页面。接下来通过本文给大家介绍JavaEE使用过滤器实现登录的相关知识,感兴趣的朋友一起学习吧2016-05-05SpringBoot整合SpringBoot-Admin实现监控应用功能
本文主要介绍如何整合Spring Boot Admin,以此监控Springboot应用,文中有相关的示例代码供大家参考,需要的朋友可以参考下2023-05-05
最新评论