zoukankan      html  css  js  c++  java
  • 【转】Mybatis中进行批量更新

    转自:https://blog.csdn.net/xyjawq1/article/details/74129316

    背景描述:通常如果需要一次更新多条数据有两个方式,(1)在业务代码中循环遍历逐条更新。(2)一次性更新所有数据(更准确的说是一条sql语句来更新所有数据,逐条更新的操作放到数据库端,在业务代码端展现的就是一次性更新所有数据)。两种方式各有利弊,下面将会对两种方式的利弊做简要分析,主要介绍第二种方式在mybatis中的实现。

    <update id="updateBatch" parameterType="java.util.List">
            update mydata_table
            <trim prefix="set" suffixOverrides=",">
                <trim prefix="status =case" suffix="end,">
                    <foreach collection="list" item="item" index="index">
                         when id=#{item.id} then #{item.status}
                    </foreach>
                </trim>
            </trim>
            where id in
            <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
                #{item.id,jdbcType=BIGINT}
            </foreach>
        </update>

    其中when...then...sql中的"switch" 语法。这里借助mybatis<foreach>语法来拼凑成了批量更新的sql,上面的意思就是批量更新idupdateBatch参数所传递List中的数据的status字段。

    <trim>属性说明 
    1.prefix,suffix 表示在trim标签包裹的部分的前面或者后面添加内容 
    2.如果同时有prefixOverrides,suffixOverrides 表示会用prefix,suffix覆盖Overrides中的内容。 
    3.如果只有prefixOverrides,suffixOverrides 表示删除开头的或结尾的xxxOverides指定的内容。

    上述代码转化成sql如下:

    update mydata_table 
        set status = 
        case
            when id = #{item.id} then #{item.status}//此处应该是<foreach>展开值
            ...
        end
        where id in (...);

    整体批量更新的写法如下:

    <update id="updateBatch" parameterType="java.util.List">
            update mydata_table
            <trim prefix="set" suffixOverrides=",">
                <trim prefix="status =case" suffix="end,">
                     <foreach collection="list" item="item" index="index">
                         <if test="item.status !=null and item.status != -1">
                             when id=#{item.id} then #{item.status}
                         </if>
                         <if test="item.status == null or item.status == -1">
                             when id=#{item.id} then mydata_table.status//原数据
                         </if>
                     </foreach>
                </trim>
            </trim>
            where id in
            <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
                #{item.id,jdbcType=BIGINT}
            </foreach>
        </update>
  • 相关阅读:
    网站开发综合技术 一 JavaScript简介 二JavaScript语法
    网站开发综合技术 第二部分 CSS样式表
    网站开发综合技术 第一部分HTML 1.3.2表单
    网站开发综合技术 HTML
    C#基础 结构体 枚举类型
    C#基础 out传值
    C#基础 函数部分
    C#基础 特殊集合
    ASP.NET MVC案例教程(基于ASP.NET MVC beta)——第一篇:准备工作
    ASP.Net中页面传值的几种方式
  • 原文地址:https://www.cnblogs.com/dawnyxl/p/9562346.html
Copyright © 2011-2022 走看看