Mybatis批量事务处理
Posted JAGNIG
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
以上是关于Mybatis批量事务处理的主要内容,如果未能解决你的问题,请参考以下文章
MyBatis批处理工具类MyBatisBatchHelper.java