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>

  • 相关阅读:
    Android开发环境搭建全程演示(jdk+eclip+android sdk)
    mysql UDF接口 网络编程(代码改进版非阻塞,超时重传)
    HTTP_POST———使用mysql_udf与curl库完成http_post通信模块(mysql_udf,multi_curl,http,post)
    Linux自动更新时间
    CentOS下设置Mysql的root密码
    CentOS yum安装LAMP环境
    Nagios远程监控软件的安装与配置详解
    Android开发之旅:环境搭建及HelloWorld
    CentOS 6.3安装配置LAMP服务器(Apache+PHP5+MySQL)
    c#,winform,show,showdialog,子窗体,父窗体,传值,输入正确
  • 原文地址:https://www.cnblogs.com/threeboke/p/15338383.html
Copyright © 2011-2022 走看看