today a question let me happy(抓狂)
头儿分了一个小任务,让修改循环调用dao层的那些不啦不啦不啦,鉴于之前写过批量更新的玩意,so 很快代码就修改完了,but 测的时候发现总是报错,很诡异,mmp 万分不解,以前就是这么写的,为嘛在这个项目就GG了?
后来还是广大人民群众给我指了条明道。OK,let us see
方法一:
<update id="updateByPrimaryKeyBatch" parameterType="java.util.Map">
<foreach collection="infos" item="item" >
update ${t_sr_process_detail}
<set>
<if test="item.tenantId != null and item.tenantId != ''">
TENANT_ID = #{item.tenantId,jdbcType=VARCHAR},
</if>
<if test="item.lgId != null">
LG_ID = #{item.lgId,jdbcType=BIGINT},
</if>
<if test="item.routeLgId != null">
ROUTE_LG_ID = #{item.routeLgId,jdbcType=BIGINT},
</if>
.....
</set>
where DSPS_PROC_ID = #{item.dspsProcId,jdbcType=BIGINT};
</foreach>
</update>
这就是我最先想到的,直接循环,构造出多条update语句 但是,很不幸的是 mysql默认不支持这种写法,其实它是不支持多条以‘;’分割的sql
解决方式:在jdbcURL配置追加:allowMultiQueries=true
方法二:
<update id="updateByPrimaryKeyBatch" parameterType="java.util.Map">
update ${t_sr_process_detail}
<trim prefix="set" suffixOverrides=",">
<trim prefix="TENANT_ID =case" suffix="end,">
<foreach collection="infos" item="item">
<if test="item.tenantId !=null and item.tenantId != ''">
when DSPS_PROC_ID=#{item.dspsProcId} then #{item.tenantId,jdbcType=VARCHAR}
</if>
</foreach>
</trim>
<trim prefix="LG_ID =case" suffix="end,">
<foreach collection="infos" item="item">
<if test="item.lgId != null">
when DSPS_PROC_ID=#{item.dspsProcId} then #{item.lgId,jdbcType=BIGINT}
</if>
</foreach>
</trim>
<trim prefix="ROUTE_LG_ID =case" suffix="end,">
<foreach collection="infos" item="item">
<if test="item.routeLgId != null">
when DSPS_PROC_ID=#{item.dspsProcId} then #{item.routeLgId,jdbcType=BIGINT}
</if>
</foreach>
</trim>
<trim prefix="WRKFM_ID =case" suffix="end,">
<foreach collection="infos" item="item">
<if test="item.wrkfmId != null">
when DSPS_PROC_ID=#{item.dspsProcId} then #{item.wrkfmId,jdbcType=BIGINT}
</if>
</foreach>
</trim>
.....
</trim>
where DSPS_PROC_ID in
<foreach collection="infos" item="item" separator="," open="(" close=")">
#{item.dspsProcId,jdbcType=BIGINT}
</foreach>
</update>
方法二据说效率高,其实不然,经过测试,发现方法二的速度明显慢与方法一,因为参数太多,使用case when 则每个参数都会循环,so we checked the first method .