解决mybatis批量更新(update foreach)失败的问题

网友投稿 469 2023-02-17

解决mybatis批量更新(update foreach)失败的问题

如下所示:

update sys_issue

first_class = #{item.first},

second_class = #{item.second},

updated_time = now()

where id = #{item.Id}

报错如下:

The error occurred while setting parameters

问题描述:

上网查询说是 配置mysql的时候没有开启批量插入,就查询了项目 是否 配置了 allowMultiQueries=true ,发现本地和线上都配置了该语句,问题没出在这。那么问题出在哪呢?后来发现是由于线上将 & 变成了 & 造成的。

* 前后对比如下:*

修http://改前:

jdbc.url=jdbc:mysql://XXX/abc?useUnicode=true&zeroDateTimeBehaviofDemIOKpEr=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 xxxxxx

xxx= #{item.xxx,jdbcType=BIGINT},

......

where id =#{item.id}

经过代码排查,以及批量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

经测试,完美解决此问题。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:MyBatis注解方式之@Update/@Delete使用详解
下一篇:Leetcode常见链表问题及代码示例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~