• 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>

  • 相关阅读:
    codeforces 645C. Enduring Exodus
    test markdown
    codeforces 817C Really Big Numbers
    797C C. Minimal string
    ubuntu配置安卓开发环境记录
    常用网址
    Mysql/Oracle/达梦中数据字典表
    Hadoop0.20.2中MapReduce读取gb2312文件出现乱码问题
    凝思磐石4.2系统字符编码的修改
    hadoop学习(三)HDFS常用命令以及java操作HDFS
  • 原文地址:https://www.cnblogs.com/threeboke/p/15338383.html
Copyright © 2020-2023  润新知