zoukankan      html  css  js  c++  java
  • mysql批量update更新,mybatis中批量更新操作

    在日常开发中,有时候会遇到批量更新操作,这时候最普通的写法就是循环遍历,然后一条一条地进行update操作。但是不管是在服务端进行遍历,还是在sql代码中进行遍历,都很耗费资源,而且性能比较差,容易造成阻塞。

    Mysql没有提供直接的方法来实现批量更新,但可以使用case when语法来实现这个功能。

    Mysql中代码示例:

    UPDATE tablename
        SET sort = CASE id 
            WHEN 1 THEN 'sort1'
            WHEN 2 THEN 'sort2'
            WHEN 3 THEN 'sort3'
        END, 
        updateuserid = CASE id 
            WHEN 1 THEN 'updateuserid1'
            WHEN 2 THEN 'updateuserid2'
            WHEN 3 THEN 'updateuserid3'
        END
    WHERE id IN (1,2,3)

    sql释义:

    如果id为1,则sort的值为sort1,updateuserid的值为updateuserid1;

    如果id为2,则sort的值为sort2,updateuserid的值为updateuserid2;

    如果id为3,则sort的值为sort3,updateuserid的值为updateuserid3;以此类推。


    Mybatis中代码示例:

    <update id="updateBatch" parameterType="list">
            update t_mt_sm_dept
            <trim prefix="set" suffixOverrides=",">
                <trim prefix=" sort = case" suffix="end,">
                    <foreach collection="list" item="i" index="index">
                        <if test="sort != '' and sort != null">
                            when id=#{i.id} then #{i.sort}
                        </if>
                    </foreach>
                </trim>
                <trim prefix="updateuserid = case" suffix="end,">
                    <foreach collection="list" item="i" index="index">
                        <if test="updateuserid != '' and updateuserid != null">
                            when id=#{i.id} then #{i.updateuserid}
                        </if>
                    </foreach>
                </trim>
                <trim prefix="updateusername = case" suffix="end,">
                    <foreach collection="list" item="i" index="index">
                        <if test="updateusername != '' and updateuserid != null">
                            when id=#{i.id} then #{i.updateusername}
                        </if>
                    </foreach>
                </trim>
            </trim>
            where
            <foreach collection="list" separator="or" item="i" index="index">
                id = #{i.id}
            </foreach>
        </update>

    java中代码:

       /**
         * 批量修改排序
         */
        int updateBatch(List<SmDept> smDeptList);
  • 相关阅读:
    TCP IP基础知识的复习
    Design Pattern: Singleton 模式
    解决Win7下安装VS2010不显示序列号框的两种方法
    字典树(Trie tree)
    在VS如何查看汇编代码
    使用模板实现编译期间多态
    一段c++代码小例子
    C++ 虚函数表解析
    C++问题:if( input.rdstate() & std::ios::failbit )
    Design Pattern: Adapter 模式 Class Adapter
  • 原文地址:https://www.cnblogs.com/hooly/p/10625594.html
Copyright © 2011-2022 走看看