Mybatis批量事务处理

 /**
       * 批量提交数据
       * @param sqlSessionFactory
       * @param mybatisSQLId SQL语句在Mapper XML文件中的ID
       * @param commitCountEveryTime 每次提交的记录数
       * @param list 要提交的数据列表
       * @param logger 日志记录器
       */
      private <T> void batchCommit(SqlSessionFactory sqlSessionFactory, String mybatisSQLId, int commitCountEveryTime, List<T> list, Logger logger) {
         SqlSession session = null;
         try {
             session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
             int commitCount = (int) Math.ceil(list.size() / (double) commitCountEveryTime);
             List<T> tempList = new ArrayList<T>(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);

猜你喜欢

转载自www.cnblogs.com/jagng951014/p/9462576.html