优秀的编程知识分享平台

网站首页 > 技术文章 正文

Mybatis 批量更新数据 Mysql批量更新数据

nanyue 2024-07-31 12:02:29 技术文章 14 ℃

通常如果需要一次更新多条数据有两个方式,(1)在业务代码中循环遍历逐条更新。(2)一次性更新所有数据

1 批量更新相同的值 不同的条件

如这里根据订单ID来更新订单表中的两个值

1.1 java中对应的接口

//DtsOrder 是我定义的一个普通的实体类
 void updateException(@Param("sendFaileList") List<DtsOrder> sendFaileList,@Param("now") LocalDateTime now);
<!--批量更新-->
<update id="updateException" parameterType="List">
    UPDATE dts_order 
    SET is_exception =2,scan_time=#{now}
    WHERE id in
    <foreach collection="sendFaileList" item="item" index="index"
             open="(" close=")" separator=",">
        #{item.id}
    </foreach>
</update>

2 批量更新不同的值 不同的条件

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

 UPDATE brand
    SET name = CASE id 
        WHEN 1 THEN 'name1'
        WHEN 2 THEN 'name2'
        WHEN 3 THEN 'name3'
    END, 
    address = CASE id 
        WHEN 1 THEN '地址1'
        WHEN 2 THEN '地址2'
        WHEN 3 THEN '地址3'
    END
WHERE id IN (1,2,3)

这条sql的意思是,如果id为1,则name的值为name1,address 的值为地址1;依此类推。

<update id="updatebrandList" parameterType="list">
    update brand
    <trim prefix="set" suffixOverrides=",">
    
        <trim prefix="name=case" suffix="end,">
            <foreach collection="list" item="item" index="index">
                <if test="item.name!=null">
                    when id=#{item.id} then #{item.name}
                </if>
            </foreach>
        </trim>
        
        <trim prefix="address =case" suffix="end,">
            <foreach collection="list" item="item" index="index">
                <if test="item.title!=null">
                    when id=#{item.id} then #{item.address}
                </if>
            </foreach>
        </trim>
    </trim>
    where
    <foreach collection="list" separator="or" item="item" index="index">
        id=#{item.id}
    </foreach>
</update>

对应的java接口

/**
 * 批量更新销量 DtsBrand 是普通的实体类
 * @param brandList
 */
void updatebrandList(@Param("list") List<DtsBrand> brandList);

3 foreach成多条sql

这种方式最简单,就是用foreach组装成多条update语句,但Mybatis映射文件中的sql语句默认是不支持以" ; " 结尾的,也就是不支持多条sql语句的执行。所以需要在连接mysql的url上加 &allowMultiQueries=true 这个才可以执行。

<update id="updatebrandList"  parameterType="java.util.List">  
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update tableName
        <set>
            name=${item.name},
            name2=${item.name2}
        </set>
        where id = ${item.id}
    </foreach>      
</update>

4 批量更新逐条更新

逐条更新这种方式显然是最简单,也最不容易出错的,即便出错也只是影响到当条出错的数据,而且可以对每条数据都比较可控,更新失败或成功,从什么内容更新到什么内容,都可以在逻辑代码中获取,

这种方式最大的问题就是效率问题,逐条更新,每次都会连接数据库,然后更新,再释放连接资源(虽然通过连接池可以将频繁连接数据的效率大大提高,抗不住数据量大),这中损耗在数据量较大的时候便会体现出效率问题

最近发表
标签列表