mybatisPlus 批量插入数据SQLServer数据库

本文讨论了在Spring框架中,当使用SqlSessionFactory处理多数据源时,如何重写批量插入方法以提高性能,包括数据分批处理、事务管理和异常处理。
摘要由CSDN通过智能技术生成
SQLServer原因需要重写批量插入方法。
ps:注入SqlSessionFactory 时,如果是多数据源,需要@Qualifier指定数据源。

@Autowired
private SqlSessionFactory sqlSessionFactory;

public void save(String packageName, List list) {
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
    try {
        //批量插入的数据分批处理
        int batchCount = 200;//每批commit的个数
        int batchIndex = (int) Math.ceil(list.size() / (double)batchCount);// 每批下标
        List tempList = new ArrayList<>(batchCount);
        int start ,stop ;
        for (int i = 0; i < batchIndex ; i++) {
            tempList.clear();
            start = i * batchCount;
            stop = Math.min(i * batchCount + batchCount - 1, list.size() - 1);
            logger.info("条数区间:" + start + " - " + stop);
            for (int j = start; j <= stop; j++) {
                tempList.add(list.get(j));
            }
            sqlSession.insert(packageName, tempList);
            sqlSession.commit();
            sqlSession.clearCache();
            logger.info("已经插入" + (stop + 1) + " 条");
        }
    } catch (Exception e) {
        e.printStackTrace();
        sqlSession.rollback();
    }finally {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值