解決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. MySQL找出未提交事務(wù)的SQL實(shí)例淺析2. Mysql故障排除:Starting MySQL. ERROR! Manager of pid-file quit without updating file3. Oracle PL/SQL語(yǔ)言初級(jí)教程之操作和控制語(yǔ)言4. 講解SQL Server數(shù)據(jù)庫(kù)備份的多種方式5. MySql分組后隨機(jī)獲取每組一條數(shù)據(jù)的操作6. ADODB連接access是出現(xiàn) 80004005 錯(cuò)誤的解決方法7. 如何安裝MySQL 壓縮包8. Oracle與Access表之間的導(dǎo)入和導(dǎo)出9. IBM 數(shù)據(jù)庫(kù) DB2 9 的九大新特性(1)10. 淺談MySql 視圖、觸發(fā)器以及存儲(chǔ)過(guò)程
