解決mybatis批量更新(update foreach)失敗的問題
如下所示:
<!--批量更新報表 --> <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>
報錯如下:
The error occurred while setting parameters
問題描述:
上網(wǎng)查詢說是 配置mysql的時候沒有開啟批量插入,就查詢了項目 是否 配置了 allowMultiQueries=true ,發(fā)現(xiàn)本地和線上都配置了該語句,問題沒出在這。那么問題出在哪呢?后來發(fā)現(xiàn)是由于線上將 & 變成了 & 造成的。
* 前后對比如下:*
修改前:
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ǔ)充知識:Mybatis 批量更新失敗,單條成功
在項目開發(fā)過程中,結(jié)合業(yè)務(wù)場景,需要對某個表進(jìn)行批量更新,完成所有的業(yè)務(wù)代碼和Mybatis XML文件后,單元測試時,發(fā)現(xiàn)調(diào)用批量更新只有一條記錄時,執(zhí)行成功,傳入多條記錄,進(jìn)行批量更新時,則提示失敗,錯誤信息如下:
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)過代碼排查,以及批量update語句通過SQL工具直接執(zhí)行均能成功,排除代碼和sql語句問題,最后求助Google大神,發(fā)現(xiàn)使用mybatis進(jìn)行批量插入與更新時,必須在配置連接url時指定allowMultiQueries=true
mysql.db.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&&allowMultiQueries=true
經(jīng)測試,完美解決此問題。
以上這篇解決mybatis批量更新(update foreach)失敗的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Delphi中的Access技巧集2. Oracle數(shù)據(jù)庫中SQL語句性能調(diào)整原則3. 什么是Access數(shù)據(jù)庫4. navicat導(dǎo)入oracle導(dǎo)出的dmp文件5. MySQL全文搜索之布爾搜索6. sqlserver數(shù)據(jù)庫導(dǎo)入方法的詳細(xì)圖文教程7. SQL Server中的數(shù)據(jù)類型詳解8. Sqlserver之死鎖查詢以及批量解鎖的實現(xiàn)方法9. Oracle行級觸發(fā)器的使用操作10. MySql分組后隨機(jī)獲取每組一條數(shù)據(jù)的操作
