您的位置:首頁技術文章
文章詳情頁

解決mybatis批量更新(update foreach)失敗的問題

瀏覽:148日期:2023-10-21 10:25:20

如下所示:

<!--批量更新報表 --> <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

問題描述:

上網查詢說是 配置mysql的時候沒有開啟批量插入,就查詢了項目 是否 配置了 allowMultiQueries=true ,發現本地和線上都配置了該語句,問題沒出在這。那么問題出在哪呢?后來發現是由于線上將 & 變成了 &amp; 造成的。

* 前后對比如下:*

修改前:

jdbc.url=jdbc:mysql://XXX/abc?useUnicode=true&zeroDateTimeBehavior=convertToNull&amp;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 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)失敗的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Mybatis 數據庫
相關文章:
国产综合久久一区二区三区