直接上代码
public class MybatisBatchInsertUtil {
/**
* 批量提交数据
* todo 经过测试发现外部事务和内部事务都是生效的,很奇怪,后续测试!
*
* @param sqlSessionFactory sqlSession工厂
* @param mybatisSQLId SQL语句在Mapper XML文件中的ID
* @param list 要提交的数据列表
* @param commitCountEveryTime 每次提交的记录数
*/
public static <T> void batchCommit(SqlSessionFactory sqlSessionFactory, String mybatisSQLId, List<T> list, int commitCountEveryTime) {
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(start + 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();
log.info("batchCommit耗时:" + (endTime - startTime) + "毫秒");
} catch (Exception e) {
if (session != null) {
session.rollback();
}
log.error("##### batchCommit error!,错误原因{},当前的 SQLID 为:{},每次提交{}条,当前的 List集合为:{}", e, mybatisSQLId, commitCountEveryTime, list);
e.printStackTrace();
//必须将异常抛出
throw new RuntimeException(e);
} finally {
if (session != null) {
session.close();
}
}
}
}
对应的 执行语句:
对应的 Mybatis 入库语句,其实就是单条入库: