解決mybatis批量更新(update foreach)失敗的問(wèn)題
如下所示:
<!--批量更新報(bào)表 --> <update 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>
報(bào)錯(cuò)如下:
The error occurred while setting parameters
問(wèn)題描述:
上網(wǎng)查詢說(shuō)是 配置mysql的時(shí)候沒(méi)有開(kāi)啟批量插入,就查詢了項(xiàng)目 是否 配置了 allowMultiQueries=true ,發(fā)現(xiàn)本地和線上都配置了該語(yǔ)句,問(wèn)題沒(méi)出在這。那么問(wèn)題出在哪呢?后來(lái)發(fā)現(xiàn)是由于線上將 & 變成了 & 造成的。
* 前后對(duì)比如下:*
修改前:
jdbc.url=jdbc:mysql://XXX/abc?useUnicode=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
修改后:
jdbc.url=jdbc:mysql://XXX/abc?useUnicode=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
補(bǔ)充知識(shí):Mybatis 批量更新失敗,單條成功
在項(xiàng)目開(kāi)發(fā)過(guò)程中,結(jié)合業(yè)務(wù)場(chǎng)景,需要對(duì)某個(gè)表進(jìn)行批量更新,完成所有的業(yè)務(wù)代碼和Mybatis XML文件后,單元測(cè)試時(shí),發(fā)現(xiàn)調(diào)用批量更新只有一條記錄時(shí),執(zhí)行成功,傳入多條記錄,進(jìn)行批量更新時(shí),則提示失敗,錯(cuò)誤信息如下:
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映射批量更新的結(jié)構(gòu)如下:
<!-- 批量更新 --> <update 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>
經(jīng)過(guò)代碼排查,以及批量update語(yǔ)句通過(guò)SQL工具直接執(zhí)行均能成功,排除代碼和sql語(yǔ)句問(wèn)題,最后求助Google大神,發(fā)現(xiàn)使用mybatis進(jìn)行批量插入與更新時(shí),必須在配置連接url時(shí)指定allowMultiQueries=true
mysql.db.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&&allowMultiQueries=true
經(jīng)測(cè)試,完美解決此問(wèn)題。
以上這篇解決mybatis批量更新(update foreach)失敗的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. DB2高可用性災(zāi)難恢復(fù)(HADR)的限制2. Microsoft Office Access調(diào)整字段位置的方法3. MySQL之mysqldump的使用詳解4. navicat for mysql導(dǎo)出sql文件的方法5. 基于mysql 默認(rèn)排序規(guī)則的坑6. SQL?Server截取字符串函數(shù)操作常見(jiàn)方法7. Oracle試用到期如何刪除注冊(cè)表繼續(xù)試用30天8. Sqlserver之死鎖查詢以及批量解鎖的實(shí)現(xiàn)方法9. MySQL中列轉(zhuǎn)行和行轉(zhuǎn)列總結(jié)解決思路10. MySQL索引查詢的具體使用
