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);
  • 相关阅读:
    [JavaWeb基础] 001.简单的JavaWeb代码和Tomcat配置部署
    [程序员短壁纸]2015年05月
    [注]什么是用户?估计90%人不知道
    [注]排行榜相关知识
    [注]微信公众号的运营推广总结方案(持续更新)
    [注]6W运营法则教你盘活社区内容运营
    [注]一条牛B的游戏推送要具备哪些条件?
    [微信营销企划之路]001.环境搭建(XAMPP+WeiPHP)
    [Python基础]005.语法(4)
    Java多线程设计模式
  • 原文地址:https://www.cnblogs.com/hooly/p/10625594.html
Copyright © 2011-2022 走看看