基于SqlSessionFactory的Mybatis批量更新

8 篇文章 0 订阅

实现方式比较多,这里主要说明sqlSessionFactory实现的批量更新

1. 首先建一个spring工具类

  • 用来自定义获取Mapper类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author yanghao
 * @version SpringContextUtil.java, v 0.1 2019-09-02 17:22
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    public static Object getBean(Class T){
        try {
            return applicationContext.getBean(T);
        }catch (BeansException e){
            return null;
        }
    }

    public static Object getBean(String name){
        try {
            return applicationContext.getBean(name);
        }catch (BeansException e){
            return null;
        }
    }

}

2. 然后是批量更新逻辑

  • 入参换成自己的对象列表
  • 更改获取自己需要Mapper类
  • 单条更新方法自己编写(批量提交)
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;

/**
 * @author yanghao
 * @version BatchUpdate.java, v 0.1 2019-09-02 17:24
 */
@Slf4j
public class BatchUpdate {

    /**
     * 提交数量,到达这个数量就提交
     */
    private static int BATCH_COUNT = 1000;

    /**
     * 标签排序批量更新
     * @param list(T可以换成自己的要更新的对象)
     * @return  
     */
    public static <T extends Object> void update(List<T> list){
        if(list ==null || list.size() <= 0){
            throw new Exception("更新数据不能为空");
        }

        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory)SpringContextUtil.getBean("sqlSessionFactory");
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
            //Mapper是自己编写或者生成的mapper文件
            Mapper mapper = sqlSession.getMapper(Mapper.class);
            for (int index = 0; index < list.size(); index++) {
                //单条更新,批量提交(调用自己写好的单条更新方法)
                mapper.update(list.get(index));

                if(index != 0 && index%BATCH_COUNT == 0){
                    //每1000条提交一次
                    sqlSession.commit();
                }
            }

            //最后不足1000的数据提交
            sqlSession.commit();

        }catch (Exception e){
            log.error("批量数据更新异常 >> list = {}, error = {}", JSON.toJSONString(list), ExceptionUtils.getStackTrace(e));
            sqlSession.rollback();

            throw new Exception("批量更新异常");

        }finally {
            if(sqlSession != null){
                sqlSession.close();
            }

        }

    }

}
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MyBatis 支持批量插入操作,其实现原理是通过 JDBC 的 addBatch 和 executeBatch 方法来实现的。下面是一个基于 Oracle 数据库的批量插入示例: 首先,我们需要在 MyBatis 的 XML 配置文件中定义一个批量插入的 SQL 语句: ```xml <insert id="batchInsert" parameterType="java.util.List"> INSERT INTO user (id, name, age) VALUES <foreach collection="list" item="item" separator=","> (#{item.id}, #{item.name}, #{item.age}) </foreach> </insert> ``` 注意,这里使用了 MyBatis 的 foreach 标签来循环插入每一条数据。 然后,在 Java 代码中,我们可以使用 SqlSession 的批量插入 API 来执行批量插入操作: ```java List<User> userList = new ArrayList<>(); // 创建多个 User 对象,并添加到 userList 中 try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)) { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int batchCount = 1000; // 每批提交的数量 int batchIndex = 0; for (int i = 0; i < userList.size(); i++) { User user = userList.get(i); userMapper.insert(user); batchIndex++; if (batchIndex == batchCount || i == userList.size() - 1) { sqlSession.flushStatements(); sqlSession.clearCache(); batchIndex = 0; } } sqlSession.commit(); } ``` 这里我们使用了 ExecutorType.BATCH 执行器类型,同时设置了每批提交的数量 batchCount。在循环插入数据时,每当插入的数量达到 batchCount 或者是插入完成时,就会执行 sqlSession.flushStatements() 来提交批量插入操作。同时,为了避免内存溢出,我们在每批提交后都要执行 sqlSession.clearCache() 来清空缓存。最后,记得要执行 sqlSession.commit() 来提交所有的批量插入操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值