Mybatis中实现批量更新的几种方式

一、概述

mybatis中实现批量插入是很简单的,相比大家都知道,这里就不赘述,本文主要讲述如何实现批量更新。

下面介绍本文要讲的几种方式主要是在xml中实现,不包含需要改动代码逻辑的方法,这里,除了网上说的普通情况,还有适合mysql和oracle的批量更新方式: 1. case when 2. foreach成多条sql 3. ON DUPLICATE KEY UPDATE (mysql) 4. replace into (mysql)

这次,我要讲的就是这四种方式。

二、case when

这种方式实现的批量更新操作效率很低,而且,当更新的字段很多时,SQL语句会特别长。

<update id="updateBatch">
    update t_calendar_extend
    <trim prefix="set" suffixOverrides=",">
        <trim prefix="modify_time = case index" suffix="end,">
            <foreach collection="list" item="item">
                when #{item.index} then #{item.modifyTime}
            </foreach>
        </trim>
        <trim prefix="user_type = case index" suffix="end">
            <foreach collection="list" item="item">
                when #{item.index} then #{item.type}
            </foreach>
        </trim>
    </trim>
    <where>
        index in (
        <foreach collection="list" separator="," item="item">
            #{item.index}
        </foreach>
        )
    </where>
</update>

这里,根据index值来更新modify_time 和user_type的值,有几个字段,就要遍历几遍,效率很低。

三、foreach成多条sql

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

<update id="updateBatch"  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>

四、ON DUPLICATE KEY UPDATE

MYSQL中的ON DUPLICATE KEY UPDATE,是基于主键(PRIMARY KEY)或唯一索引(UNIQUE INDEX)使用的。

如果已存在该唯一标示或主键就更新,如果不存在该唯一标示或主键则作为新行插入。

<update id="updateBatch">
    insert into t_output_calendar (index, 
      cal_date, user_type, create_time, 
      modify_time, delete_flag
      )
    values
    <foreach collection="list" item="item" index="index"
        separator=",">
        (
        #{item.index,jdbcType=INTEGER}, 
        #{item.calDate,jdbcType=TIMESTAMP}, 
        #{item.type,jdbcType=TINYINT}, 
        #{item.createTime,jdbcType=TIMESTAMP}, 
        #{item.modifyTime,jdbcType=TIMESTAMP}, 
        #{item.deleteFlag,jdbcType=TINYINT}
        )
    </foreach>
    <!--存在即可修改下述字段的数据,注意values()中的内容是数据表中相应的字段名-->	
    ON DUPLICATE KEY UPDATE modify_time = VALUES(modify_time), user_type = VALUES(user_type);
</update>

五、replace into

msql的replace into跟insert into的用法完全一样,但是它带有更新功能:

如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。否则,直接插入新数据。

注意,它是先删除数据,然后再插入,这是和ON DUPLICATE KEY UPDATE不同的地方,如果当前的数据库用户没有删除权限,是不能使用replace into的。

示例:

<insert id="updateBatch" parameterType="java.util.List">
    replace into t_output_calendar (index, cal_date, user_type, create_time, 
      modify_time, delete_flag
      )
    values
    <foreach collection="list" item="item" index="index"
        separator=",">
        (
        #{item.index,jdbcType=INTEGER}, 
        #{item.calDate,jdbcType=TIMESTAMP}, 
        #{item.type,jdbcType=TINYINT}, 
        #{item.createTime,jdbcType=TIMESTAMP}, 
        #{item.modifyTime,jdbcType=TIMESTAMP}, 
        #{item.deleteFlag,jdbcType=TINYINT}
        )
    </foreach>
</insert>

1、insert into表示插入数据,数据库会检查主键,如果出现重复会报错;

2、replace into表示插入替换数据,需求表中有PrimaryKey,或者unique索引,如果数据库已经存在数据,则用新数据替换,如果没有数据效果则和insert into一样;

-- 存在就更新:
REPLACE INTO 表名(字段1, 字段2, ...) VALUES(值1, 值2, ...), (值1, 值2, ...);

3、insert ignore表示,如果表中如果已经存在相同的记录,则忽略当前新数据;

-- 存在就忽略:
INSERT IGNORE 表名(字段1, 字段2, ...) VALUES(值1, 值2, ...), (值1, 值2, ...);

4、on duplicate key update 使用该语法可在插入记录的时候先判断记录是否存在,如果不存在则插入,否则更新,很方便,无需执行两条SQL 

更新 100000条数据的性能就测试结果来看,测试当时使用replace into性能较好。

replace into 和 insert into on duplicate key update的不同在于:

replace into 操作本质是对重复的记录先delete 后insert,如果更新的字段不全会将缺失的字段置为缺省值,用这个要悠着点否则不小心清空大量数据可不是闹着玩的。
insert into on duplicate key update 则是只update重复记录,不会改变其它字段。

参考文章:

Mysql 批量修改四种方式效率对比(一)_mysql的replac into 效率_程序员深夜写bug的博客-CSDN博客

SpringBoot 高效批量插入万级数据,哪种方式最强? 

  • 4
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值