@Author Jacky Wang
在使用Mybatis進(jìn)行批量插入與更新的時(shí)候,遍歷一條條的操作效率太低,因此采用mybatis的動(dòng)態(tài)sql實(shí)現(xiàn)批量操作。
1. mybatis批量插入
示例如下:
這里有個(gè)注意點(diǎn):
括號(hào)的分隔不能在<foreach>標(biāo)簽里面使用close與open使用。
<insert id="batchAddTagBindingRecord" parameterType="java.util.List" useGeneratedKeys="true">
insert t_tag_binding (goods_id,status,epc,tid,op_scene,origin_id,create_date,creater,client_id)values
<foreach collection="list" item="item" index="index" separator=",">
( #{item.goodsId,jdbcType=BIGINT},
#{item.status,jdbcType=VARCHAR},
#{item.epc,jdbcType=VARCHAR},#{item.tid,jdbcType=VARCHAR},
#{item.opScene,jdbcType=VARCHAR},#{item.originId,jdbcType=BIGINT},
#{item.createDate,jdbcType=TIMESTAMP},#{item.creater,jdbcType=BIGINT}, #{item.clientId,jdbcType=BIGINT}
)
</foreach>
</insert>
2. mybatis批量更新
示例如下:
MySQL沒有提供直接的方法來實(shí)現(xiàn)批量更新,但可以使用case when語法來實(shí)現(xiàn)這個(gè)功能。
注意:最外層trim不能包where條件
<update id="batchUpdateTagStatus" parameterType="java.util.List">
update t_tag
<trim prefix="set" suffixOverrides=",">
<trim prefix="goods_id = case" suffix="end,">
<foreach collection="list" item="item" index="index">
when epc=#{item.epc} then #{item.goodsId}
</foreach>
</trim>
<trim prefix="status = case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.status!=null">
when epc=#{item.epc} then #{item.status}
</if>
</foreach>
</trim>
<trim prefix="last_update = case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.lastUpdate!=null">
when epc=#{item.epc} then #{item.lastUpdate}
</if>
</foreach>
</trim>
</trim>
where epc in
<foreach collection="list" separator="," item="item" index="index" open="(" close=")">
#{item.epc}
</foreach>
</update>