mybatis 实现批量更新

注:Mybatis实现批量更新有三种方式,分别是使用foreach标签、使用SQL的case when语句和使用动态SQL的choose语句。具体实现方法如下:

1:使用foreach标签

   <update id="pubAndTakes">
        <foreach collection="idList" item="item" separator=";" open="begin" close=";end;">
            UPDATE LY_SJS_WDZM_YXLXD_PZRY SET ZT = '1' , CJSJ = TO_CHAR(SYSDATE,'yyyy-MM-dd hh:mm:ss')
            ,BBH = #{item.bbh}
            WHERE ZT = #{item.zt} AND ID = #{item.id}
        </foreach>
    </update>

2:使用SQL的case when语句

<update id="updateBatch" parameterType="java.util.List">
    UPDATE your_table
    SET your_column1 = 
        <foreach collection="list" item="item" separator=",">
            WHEN your_id = #{item.id} THEN #{item.column1}
        </foreach>
    WHERE your_id IN
        <foreach collection="list" item="item" open="(" close=")" separator=",">
            #{item.id}
        </foreach>
</update>

3:使用 Case 语句

在 SQL 更新语句中使用 CASE 语句,根据条件进行更新。这种方式可以避免使用 foreachBatchExecutor,但对于大量数据可能性能较差。

<update id="updateBatch" parameterType="java.util.List">
    UPDATE your_table
    SET your_column1 = 
        CASE
            <foreach collection="list" item="item" separator=" ">
                WHEN your_id = #{item.id} THEN #{item.column1}
            </foreach>
        END,
    your_column2 =
        CASE
            <foreach collection="list" item="item" separator=" ">
                WHEN your_id = #{item.id} THEN #{item.column2}
            </foreach>
        END
    WHERE your_id IN
        <foreach collection="list" item="item" open="(" close=")" separator=",">
            #{item.id}
        </foreach>
</update>

这种方式的 SQL 语句会根据条件进行更新,适用于一次性批量更新较少的记录。

注:


使用BatchExecutor批处理器

MyBatis 提供了 BatchExecutor 批处理器,可以在一次数据库会话中批量执行多个 SQL 语句。这种方式需要在代码中手动创建批处理器,并调用 batch 方法执行批量更新。注意,此方式可能不支持所有数据库,因此请仔细查阅文档以确认你的数据库是否支持。

SqlSession sqlSession = sqlSessionFactory
                           .openSession(ExecutorType.BATCH, false);

YourMapper mapper = sqlSession.getMapper(YourMapper.class);
try {
    for (YourEntity entity : entities) {
        mapper.update(entity);
    }
    sqlSession.commit();
} finally {
    sqlSession.close();
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

入夏忆梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值