解決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
問題描述:
上網(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
補充知識:Mybatis 批量更新失敗,單條成功
在項目開發(fā)過程中,結合業(yè)務場景,需要對某個表進行批量更新,完成所有的業(yè)務代碼和Mybatis XML文件后,單元測試時,發(fā)現(xiàn)調用批量更新只有一條記錄時,執(zhí)行成功,傳入多條記錄,進行批量更新時,則提示失敗,錯誤信息如下:
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>
經(jīng)過代碼排查,以及批量update語句通過SQL工具直接執(zhí)行均能成功,排除代碼和sql語句問題,最后求助Google大神,發(fā)現(xiàn)使用mybatis進行批量插入與更新時,必須在配置連接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)失敗的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
關于SpringSecurity?Context?中獲取和更改當前用戶信息的問題
SpringSecurityContext在異步線程中無法獲取用戶信息,因其與請求線程綁定;此外,用戶信息更新后跳轉頁面時,身份會被降級為匿名,導致信息無法及時同步,本文給大家介紹SpringSecurity?Context?中獲取和更改當前用戶信息的問題,感興趣的朋友一起看看吧2024-09-09
聊聊spring @Transactional 事務無法使用的可能原因
這篇文章主要介紹了spring @Transactional 事務無法使用的可能原因,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Spring?Boot中獲取request的三種方式及請求過程
這篇文章主要介紹了Spring?Boot當中獲取request的三種方式,包括請求過程流程分析及response常用API,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-03-03

