mybatis批量更新的几种方式

本文探讨了三种批量更新数据库记录的方法:单次循环更新、批量设置同一值更新及灵活批量更新,并重点介绍了MyBatis中通过动态SQL实现高效灵活的批量更新案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.第一种情况,使用for循环进行更新。
List<Person> persons = ....;
    for(Person person : persons){
    update(person);
}

        这种方式更新,存在效率慢,没执行一次都需要获取一次数据库的连接,结束之后关闭,比较浪费资源。

2.第二种情况,更新某一列的值。

       

update table set column = #{value} where id in 
 <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
 	#{item.id}
</foreach>

        这种方式只能将指定Id的某一列的值设置为一样的。存在缺陷。

3.第三种情况,也是推荐使用的。

为不同的列设置不同的数据,数据量大时候批量更新使用。

<update id="batchUpdateMaterialPurchaseOrder" parameterType="java.util.List">
        update tpmc_material_purchase_order t
        <trim prefix="set" suffixOverrides=",">//update的set关键字
            <trim prefix="sys_remark =case" suffix="end,">//指定需要更新的列名,以","作为后缀
                 <foreach collection="list" item="item" index="index">
                     <if test="item.sysRemark !=null and item.sysRemark != ''">//判断参数是否为空
                         when t.id=#{item.id} then #{item.sysRemark}
                     </if>
                 </foreach>
            </trim>
             <trim prefix="review_status =case" suffix="end,">
                 <foreach collection="list" item="item" index="index">
                     <if test="item.reviewStatus !=null and item.reviewStatus != ''">
                         when t.id=#{item.id} then #{item.reviewStatus}
                     </if>
                 </foreach>
            </trim>
             <trim prefix="purchase_id =case" suffix="end,">
                 <foreach collection="list" item="item" index="index">
                     <if test="item.purchaseId !=null and item.purchaseId != ''">
                         when t.id=#{item.id} then #{item.purchaseId}
                     </if>
                 </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
            #{item.id}
        </foreach>
    </update>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值