2015-02-23 69 views
0

以下是我使用foreachupdate語句編寫的批量更新查詢。在此除了update_time之外的任何其他參數都可以爲null。 該查詢應該將對象列表作爲參數並返回void。MySQLSyntaxErrorException:Mybatis:使用foreach批量更新查詢

<update id="bulkUpdate" parameterType="java.util.List"> 
<foreach collection="list" item="item" index="index" separator=";" > 
    UPDATE 
    <include refid="tableName" /> 
    <set> 
      update_time=#{item.updateTime} 
      <if test="item.testFlg != null">, test_flg=#{item.testFlg}</if> 
      <if test="item.DueDate != null">, due_date=#{item.DueDate}</if> 
      <if test="item.versionId != null">, version_id=#{item.versionId}</if> 
    </set> 
    WHERE 
    <include refid="tableName" />.order_id=#{item.orderId} 
</foreach> 
</update> 

調試後,我發現查詢得到正確的所有非空值。不過,我得到這個令我瘋狂的錯誤。

The error occurred while setting parameters\r\n### SQL: UPDATE  glb_order_tbl  SET update_time=?                                                 , complete_due_date=?       , version_id=?  WHERE  glb_order_tbl .order_id=? ;    UPDATE  glb_order_tbl  SET update_time=?                                                 , complete_due_date=?       , version_id=?  WHERE  glb_order_tbl .order_id=? \r\n### 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 'UPDATE \n  glb_order_tbl \n  SET update_time='2015-02-24 13:01:48.608'\n ' at line 24\n; bad SQL grammar []; nested exception is 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 'UPDATE \n  glb_order_tbl \n  SET update_time='2015-02-24 13:01:48.608'\n ' at line 24" 

看來某種語法錯誤,我找不到。
我使用Java+spring+MyBatis+MySql

更新後的查詢和參數設定(組塊內)error.Please筆記可能事先已經改變

感謝。

回答

1

這裏的問題是您在foreach關閉設置opencloseseparator不正確。

在SQL,它附加在(整個SQL的開始,)末,每個update SQL與,分開。生成的sql肯定有語法錯誤。

更改它如下,它應該工作。

<foreach collection="list" item="item" index="index" separator=";"> 
+0

謝謝@Landys。在正確理解了foreach語句並根據您的答案修改了我的語句後,我能夠弄清楚這一點。但它仍然會給出同樣的錯誤,儘管在不同的線路上。 而且我能夠通過工作臺使用「錯誤」查詢進行多個更新。 我想指出,我使用簡單的mybatis執行器。我需要使用批處理執行器或什麼.. ?? – 2015-02-24 07:56:29

+0

你是否啓用jdbc url中的多個更新?如果不是,則應該將參數'allowMultiQueries = true'附加到jdbc的url中。 – Frank 2015-05-04 06:35:10