case when + forEach 实现多条件多值批量更新

case when + forEach 实现多条件多值批量更新

1、单个条件

   <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 ">
                         when id=#{item.id} then #{item.status}
                     </if>                    
                 </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
            #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>

2、多个条件

 <update id="updateBatch" parameterType="java.util.List">
    update demo_table
    <trim prefix="set" suffixOverrides=",">
        status=
        <foreach collection="list" item="item" open="case " close=" end,">
            when field2=#{item.field2} and company_id=#{item.field3} then #{item.status}
        </foreach>
        create_time =
        <foreach collection="list" item="item" open="case " close=" end,">
          when field2=#{item.field2} and company_id=#{item.field3} then
          <choose>
            <when test="item.createTime!=null">
              #{item.createTime}
            </when>
            <otherwise>now()</otherwise>
          </choose>
        </foreach>
    </trim>
    WHERE
    <foreach collection="list" item="item" open="( " separator=") or (" close=" )">
      device_num=#{item.field2} and company_id=#{item.field3}
    </foreach>
  </update>

注意:
foreach标签如果放在一条SQL外边的执行要比在一条SQL中写foreach然后根据条件循环更新的效率要低,数据量大的时候特别明显,建议foreach标签的使用写在一条SQL语句的中间

猜你喜欢

转载自blog.csdn.net/Sophia_0331/article/details/107598293