解決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)失敗的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。