【已解决】mybatis - 通过3种方式 批量更新

  • 作者: 凯哥Java(公众号:凯哥Java)
  • mybatis
  • 时间:2024-02-14 01:42
  • 552人已阅读
简介 本文凯哥(公众号:凯哥Java)来讲讲mybatis的三者中批量更新方式通过foreach批量更新通过casewhen批量更新(100条级别使用,批量更新数据太多会适得其反)通过ExecutorType.Batch批量更新一、通过foreach批量更新原始mysql的语句:update table set id=1,name="泽虞生" 

🔔🔔好消息!好消息!🔔🔔

 如果您需要注册ChatGPT,想要升级ChatGPT4。凯哥可以代注册ChatGPT账号代升级ChatGPT4

有需要的朋友👉:微信号 kaigejava2022

本文凯哥(公众号:凯哥Java)来讲讲mybatis的三者中批量更新方式

  1. 通过foreach批量更新

  2. 通过case when批量更新(100条级别使用,批量更新数据太多会适得其反)

  3. 通过ExecutorType.Batch批量更新

一、通过foreach批量更新

原始mysql的语句:

update table set id=1,name="泽虞生" where id = 1;
update table set id=2,name="泽虞生" where id = 2;
update table set id=3,name="泽虞生" where id = 3;
...

对应的mybatis的写法:

<foreach collection="list" item="i" index="index" open="" close="" separator=";">
     UPDATE table
     <trim prefix="set" suffixOverrides=",">
         <if test="i.id!=null">id= #{i.id}</if>
         <if test="i.name!=null">name= #{i.name}</if>
      </trim>
      WHERE id= #{i.id} and is_deleted = 0
</foreach>

需要注意:

  1. 分隔符是分号。open和close都是空的

  2. 需要有主键或者是能够唯一区分的字段


二、通过case when批量更新

原始mysql语句写法:

update table set
id = case 
	when id = 1 then 1 
	when id = 2 then 2
	when id = 3 then 3 end,
name = case
	when id = 1 then '泽虞生1'
	when id = 2 then '泽虞生2'
	when id = 3 then '泽虞生3' end,
where id in (1,2,3)
...

对应的mybatis的写法:

UPDATE sms_send_callback
<trim prefix="set" suffixOverrides=",">
      <trim prefix="id=case" suffix="end,">
            <foreach collection="list" item="i" index="index">
                    <if test="i.id!=null">
                        when id=#{i.id} then #{i.id}    
                    </if>
            </foreach>
      </trim>
      <trim prefix="name=case" suffix="end,">
            <foreach collection="list" item="i" index="index">
                    <if test="i.name!=null">
                        when id=#{i.id} then #{i.name}
                    </if>
             </foreach>
      </trim>
</trim>
WHERE id IN
<trim prefix="(" suffix=")">
     <foreach collection="list" separator=", " item="i" index="index">
         #{i.id}
     </foreach>
</trim>



三、通过ExecutorType.Batch批量更新

@Autowired
private SqlSessionFactory sqlSessionFactory;
 
public void updateBatchByExecutorType(){
        // 初始化更新数据
        List<Table> tables = initUpdateBatchData(1000, "批量手动更新数据");
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        TableMapper mapper = sqlSession.getMapper(TableMapper.class);
        int i = 0;
        for (Table table : tables){
            mapper.updateByPrimaryKeySelective(table);
            // 每100条执行一次
            if ((i + 1) % 100 == 0){
                sqlSession.flushStatements();
            }
            i++;
        }
        sqlSession.flushStatements();
}



TopTop