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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM