zoukankan      html  css  js  c++  java
  • mybatis多条件多值批量更新

    mysql并没有提供直接的方法来实现批量更新,但是可以用点小技巧来实现。

    这里使用了case when 这个小技巧来实现批量更新。

    举个例子:

      UPDATE 表名 SET
        display_order = CASE id
            WHEN 1 THEN 3
            WHEN 2 THEN 4
            WHEN 3 THEN 5
        END
    WHERE id IN (1,2,3)

    这句sql的意思是,更新display_order 字段:

        如果id=1 则display_order 的值为3,
        如果id=2 则 display_order 的值为4,
        如果id=3 则 display_order 的值为5。

    即是将条件语句写在了一起。

    这里的where部分不影响代码的执行,但是会提高sql执行的效率。

    确保sql语句仅执行需要修改的行数,这里只有3条数据进行更新,而where子句确保只有3行数据执行。

    单个条件批量更新:

      <update id="updateBatch" parameterType="java.util.List">
            update 表名
            <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>

    多条件批量更新:


    <update id="updateBatch" parameterType="java.util.List">
        update 表名
        <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>

  • 相关阅读:
    Xamarin.Android和UWP之MVVM的简单使用(二)
    Xamarin.Android和UWP之MVVM的简单使用(一)
    那些年用过的xUnit.net的简单用法
    Xamarin.Android之给我们的应用加点过渡效果
    Xamarin.Android之Splash的几种简单实现
    Xamarin.Android之布局文件智能提示问题
    Xamarin.Android之Spinner的简单探讨
    Xamarin.Android之封装个简单的网络请求类
    Xamarin.Android再体验之简单的登录Demo
    【分库分表】sharding-jdbc实践—分库分表入门
  • 原文地址:https://www.cnblogs.com/threeboke/p/15338383.html
Copyright © 2011-2022 走看看