Mybatis批量事务处理

 /**
       * 批量提交数据
       * @param sqlSessionFactory
       * @param mybatisSQLId SQL语句在Mapper XML文件中的ID
       * @param commitCountEveryTime 每次提交的记录数
       * @param list 要提交的数据列表
       * @param logger 日志记录器
       */
      private  void batchCommit(SqlSessionFactory sqlSessionFactory, String mybatisSQLId, int commitCountEveryTime, List list, Logger logger) {
         SqlSession session = null;
         try {
             session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
             int commitCount = (int) Math.ceil(list.size() / (double) commitCountEveryTime);
             List tempList = new ArrayList(commitCountEveryTime);
             int start, stop;
             Long startTime = System.currentTimeMillis();
             for (int i = 0; i < commitCount; i++) {
                 tempList.clear();
                 start = i * commitCountEveryTime;
                 stop = Math.min(i * commitCountEveryTime + commitCountEveryTime - 1, list.size() - 1);
                 for (int j = start; j <= stop; j++) {
                     tempList.add(list.get(j));
                 }
                 session.insert(mybatisSQLId, tempList);
                 session.commit();
                 session.clearCache();
             }
             Long endTime = System.currentTimeMillis();
             logger.debug("batchCommit耗时:" + (endTime - startTime) + "毫秒");
         } catch (Exception e) {
             logger.error("batchCommit error!", e);
             e.printStackTrace();
             session.rollback();
         } finally {
             if (session != null) {
                 session.close();
             }
         }
     }


SqlSessionFactory获取方式:
SqlSessionFactory sqlSessionFactory = ctx.getBean(SqlSessionFactory.class);
SqlSession session = null;
session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);

转载于:https://www.cnblogs.com/jagng951014/p/9462576.html

你可能感兴趣的:(Mybatis批量事务处理)