【转】Mybatis中进行批量更新

转自:https://blog.csdn.net/xyjawq1/article/details/74129316

背景描述:通常如果需要一次更新多条数据有两个方式,(1)在业务代码中循环遍历逐条更新。(2)一次性更新所有数据(更准确的说是一条sql语句来更新所有数据,逐条更新的操作放到数据库端,在业务代码端展现的就是一次性更新所有数据)。两种方式各有利弊,下面将会对两种方式的利弊做简要分析,主要介绍第二种方式在mybatis中的实现。

<update id="updateBatch" parameterType="java.util.List">
        update mydata_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="status =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                     when id=#{item.id} then #{item.status}
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
            #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>

其中when...then...sql中的"switch" 语法。这里借助mybatis<foreach>语法来拼凑成了批量更新的sql,上面的意思就是批量更新idupdateBatch参数所传递List中的数据的status字段。

<trim>属性说明 
1.prefix,suffix 表示在trim标签包裹的部分的前面或者后面添加内容 
2.如果同时有prefixOverrides,suffixOverrides 表示会用prefix,suffix覆盖Overrides中的内容。 
3.如果只有prefixOverrides,suffixOverrides 表示删除开头的或结尾的xxxOverides指定的内容。

上述代码转化成sql如下:

update mydata_table 
    set status = 
    case
        when id = #{item.id} then #{item.status}//此处应该是<foreach>展开值
        ...
    end
    where id in (...);

整体批量更新的写法如下:

<update id="updateBatch" parameterType="java.util.List">
        update mydata_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="status =case" suffix="end,">
                 <foreach collection="list" item="item" index="index">
                     <if test="item.status !=null and item.status != -1">
                         when id=#{item.id} then #{item.status}
                     </if>
                     <if test="item.status == null or item.status == -1">
                         when id=#{item.id} then mydata_table.status//原数据
                     </if>
                 </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
            #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>
原文地址:https://www.cnblogs.com/dawnyxl/p/9562346.html