MyBatis+DB2批量更新时报-104
MyBatis原来的写法
<借鉴一下网友的代码>
<update id="updateBatch" parameterType="java.util.List" >
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update standard_relation
<set >
<if test="item.standardFromUuid != null" >
standard_from_uuid = #{item.standardFromUuid,jdbcType=VARCHAR},
</if>
<if test="item.standardToUuid != null" >
standard_to_uuid = #{item.standardToUuid,jdbcType=VARCHAR},
</if>
<if test="item.gmtModified != null" >
gmt_modified = #{item.gmtModified,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{item.id,jdbcType=BIGINT}
</foreach>
</update>
从代码本身来看,并没有什么问题,但是一执行,只要是多条数据,就会报错-104,一开始比较诧异,把错误日志里的sql拿到数据库操作平台上执行,也没问题,经过多次执行发现,当批量的数据只有一条时,能正常更新,这时候就想到了,可能是mybatis的配置上出了问题,仔细分析插入多条数据时的sql时,发现打印的sql是由多个分号隔开的,说明此时我的项目的mybatis是不支持在一个标签中写多条sql语句的。
解决方式
问题的源头已经找到了,解决问题的方式有几种,网上更多的是让你改变myBatis的配置,让你的myBatis可以在一个标签中写多个sql语句,但这种方式是有危险性的,比如无法控制事务,那只能在sql上下文章了,网上也有很多网友给出了写法,这里我也贴出一份我的写法。
<版本1>
<update id="updateBatch" parameterType="java.util.List">
update standard_relation
standard_from_uuid =
<foreach collection="list" item="item" index="index" separator="" open="(case" close="end)">
when id = #{item.id,jdbcType=BIGINT} then #{item.standardFromUuid,jdbcType=VARCHAR}
</foreach>
,standard_to_uuid =
<foreach collection="list" item="item" index="index" separator="" open="(case" close="end)">
when id = #{item.id,jdbcType=BIGINT} then #{item.standardToUuid,jdbcType=VARCHAR}
</foreach>
,gmt_modified =
<foreach collection="list" item="item" index="index" separator="" open="(case" close="end)">
when id = #{item.id,jdbcType=BIGINT} then #{item.gmtModified,jdbcType=TIMESTAMP}
</foreach>
where id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.id,jdbcType=BIGINT}
</foreach>
</update>
但是执行还是会报错,DB2 -418 42610 参数标识符使用无效
解决方式:
<update id="updateBatch" parameterType="java.util.List">
update standard_relation
standard_from_uuid =
<foreach collection="list" item="item" index="index" separator="" open="(case" close="end)">
when id = '${item.id}' then '${item.standardFromUuid}'
</foreach>
,standard_to_uuid =
<foreach collection="list" item="item" index="index" separator="" open="(case" close="end)">
when id = '${item.id}' then '${item.standardToUuid}'
</foreach>
,gmt_modified =
<foreach collection="list" item="item" index="index" separator="" open="(case" close="end)">
when id = '${item.id}' then '${item.gmtModified}'
</foreach>
where id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
'${item.id}'
</foreach>
</update>
最终完美执行
以上只是我遇到问题的一种解决方式,仅供参考,如有建议,可以私信一同交流!