Mybaties批量更新一直報錯,意思是在Mybaties的xml中執行sql的時候多了個“;”,因爲在Mybaties的xml中在SQL語句的結尾是不能加上“;”的加上後就會報下面的錯誤。但是SQL有必須這樣配置。
<foreach collection="list" separator=";" index="index" item="item">
### Cause: java.sql.SQLSyntaxErrorException: ORA-00911: 無效字符
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: ORA-00911: 無效字符
最後通過爲foreach設置open和close屬性來解決問題(此處另一篇文章講解該標籤作用),在這裏設置兩個標籤如下:
<foreach collection="list" separator=";" index="index" open="begin" close=";end;" item="item">
讓begin和end;包裹生成的SQL即可。注意如果數據庫爲Mysql還要在Mysql的配置連接後加上;allowMultiQueries=true表示一次可以項向數據庫提交執行多個SQL。
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
整個Mybaties的批量新增SQL如下:
<update id="batchUpdate" parameterType="java.util.List">
<foreach collection="list" separator=";" index="index" open="begin" close=";end;" item="item">
update DATA_TABLE
<set>
<if test="item.name != null" >
NAME = #{item.name, jdbcType=VARCHAR},
</if>
<if test="item.shortName != null" >
SHORT_NAME = #{item.shortName, jdbcType=VARCHAR},
</if>
<if test="item.deptCode != null" >
CODE = #{item.code, jdbcType=VARCHAR},
</if>
</set>
where ID = #{item.id,jdbcType=VARCHAR}
</foreach>
</update>
執行結果:
BEGIN
UPDATE DATA_TABLE SET NAME = ?, SHORT_NAME = ?, DEPT_CODE = ? WHERE ID = ? ;
UPDATE DATA_TABLE SET NAME = ?, SHORT_NAME = ?, DEPT_CODE = ? WHERE ID = ? ;
UPDATE DATA_TABLE SET NAME = ?, SHORT_NAME = ?, DEPT_CODE = ? WHERE ID = ? ;
END ;