【MyBatis】关于MyBatis批量更新的几种方式

1. Java代码循环执行sql,逐条更新

这种方式就是将需要更新的数据,循环调用update方法去更新数据,实现代码如下:

public void test() {
        // 需要更新的集合
        List<HashMap<String, Object>> updateMap = new ArrayList<>();
        HashMap<String, Object> param = new HashMap<>(3);
        param.put("name", "test");
        param.put("price", 12.1);
        param.put("id", 1223);
        updateMap.add(param);
        // 循环执行更新
        updateMap.stream().forEach(map -> {
            sqlSession.update("update.updatePrice", map);
        });
    }

XML文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="update">
    <!--更新price表-->
    <update id="updatePrice">
        update price_info
        <set>
            <if test="name != null and name !=''">
                name = #{name},
            </if>
            <if test="price != null">
                sex = #{price}
            </if>
        </set>
        where id = #{id}
    </update>
</mapper>

这种方法显而易见的最大问题就是每次都要去操作数据库,数据量大了可能会造成sql阻塞但是效率还是挺高。

2. 通过传入list进行遍历

 public void test() {
        // 需要更新的集合
        List<HashMap<String, Object>> updateMap = new ArrayList<>();
        HashMap<String, Object> param = new HashMap<>(3);
        param.put("id", "1234");
        param.put("status", "2");
        param.put("price", "22");
        updateMap.add(param);
        sqlSession.update("supplierSku.updatePrice", updateMap);
    }

XML文件如下:

<update id="updatePrice">
        <foreach collection="list" item="item" index="index" open="" close="" separator=";">
            update price_info
            <set>

                <if test="item.status != null and item.status != ''">
                    status = #{item.status},
                </if>
                <if test="item.price != null and item.price != ''">
                    price = #{item.price},
                </if>
            </set>
            where id = #{item.id}
        </foreach>
    </update>

其实这种和第一种方式一样,只是吧循环list放到了XML中去处理。

3. 通过case,when变相实现批量更新

    public void test() {
        // 需要更新的集合
        List<HashMap<String, Object>> updateMap = new ArrayList<>();
        HashMap<String, Object> param = new HashMap<>(3);
        param.put("id", "1234");
        param.put("status", "2");
        param.put("price_end_date", new Date());
        updateMap.add(param);
        sqlSession.update("supplierSku.updateSupplierSkuPrice", updateMap);
    }

XML文件如下:

<update id="updateSupplierSkuPrice" parameterType="java.util.List">
        update price_info
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="status =case" suffix="end,">
                <foreach collection="list" item="i" index="index">
                    <if test="i.status!=null and i.status!= ''">
                        when id=#{i.id} then #{i.status}
                    </if>
                </foreach>
            </trim>
            <trim prefix="price_end_date =case" suffix="end,">
                <foreach collection="list" item="i" index="index">
                    <if test="i.price_end_date!=null">
                        when id=#{i.id} then #{i.price_end_date}
                    </if>
                </foreach>
            </trim>
        </trim>
        where
        <foreach collection="list" separator="or" item="i" index="index" >
            id=#{i.id}
        </foreach>
    </update>

使用case,when最后会变成一条sql语句,但是每次都得去遍历list集合,数据量大了会影响效率问题

PS:只有string类型的数据才能使用 xxx != ’ ’ 当其他类型使用就会报类型转换错误

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MyBatis实现批量更新有多种方式,下面介绍几种常用的实现方式。 1. 使用foreach标签 使用foreach标签可以方便地实现批量更新。具体实现步骤如下: 在Mapper XML文件中定义批量更新的SQL语句,例如: ``` <update id="batchUpdate"> <foreach collection="list" item="item" separator=";"> update table_name set column_name1 = #{item.columnName1}, column_name2 = #{item.columnName2} where id = #{item.id} </foreach> </update> ``` 在Java代码中调用该SQL语句,例如: ``` List<Entity> entityList = new ArrayList<>(); // 添加需要更新的实体对象到集合中 int result = sqlSession.update("namespace.batchUpdate", entityList); ``` 2. 使用BatchExecutor BatchExecutor是MyBatis提供的批量执行器,可以批量执行SQL语句。具体实现步骤如下: 在MyBatis配置文件中配置BatchExecutor,例如: ``` <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> <executor type="BATCH"/> </environment> </environments> </configuration> ``` 在Java代码中使用BatchExecutor执行批量更新,例如: ``` List<Entity> entityList = new ArrayList<>(); // 添加需要更新的实体对象到集合中 SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); try { for (Entity entity : entityList) { sqlSession.update("namespace.update", entity); } sqlSession.commit(); } finally { sqlSession.close(); } ``` 注意事项: - BatchExecutor需要在MyBatis配置文件中进行配置,且需要使用JDBC事务管理器。 - 使用BatchExecutor进行批量更新时,需要手动管理事务和提交事务。 - 批量更新的数量受到数据库服务器和网络环境等多方面因素的影响,可能会出现性能瓶颈。建议在具体应用中进行测试和优化。 除了以上两种方式,还可以使用MyBatis提供的批量更新方法,例如: ``` List<Entity> entityList = new ArrayList<>(); // 添加需要更新的实体对象到集合中 int result = sqlSession.update("namespace.batchUpdate", entityList); ``` 这种方式需要在Mapper XML文件中定义批量更新的SQL语句,并且使用`List`类型作为参数传入SQL语句中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值