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 ;