代码示例:
package com.ly.cloud.util;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import com.google.common.collect.Lists;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @Author
* @Date Created in 2023/12/25 15:57
* @DESCRIPTION: mybatis快速批量插入 数据 工具类
* @Version V1.0
*/
@Component
public class MyBatisBatchExecutorUtil {
private static final Logger logger = LoggerFactory.getLogger(MyBatisBatchExecutorUtil.class);
@Resource
private SqlSessionFactory sqlSessionFactory;
private static MyBatisBatchExecutorUtil utils;
@PostConstruct
public void init() {
utils = this;
utils.sqlSessionFactory = this.sqlSessionFactory;
}
/**
* 批量提交数据
*
* @param mapperClass Mapper 类
* @param dataList 要提交的数据列表
*/
public static <T> void batchCommit(Class<?> mapperClass, String mybatisSqlId, List<T> dataList) {
if (dataList == null || dataList.isEmpty()) {
return;
}
SqlSession session = null;
int commitCountEveryTime = 500;
try {
long startTime = System.currentTimeMillis();
session = utils.sqlSessionFactory.openSession(ExecutorType.BATCH, false);
List<List<T>> groupList = Lists.partition(dataList, commitCountEveryTime);
for (List<T> tempList : groupList) {
session.insert(mapperClass.getName() + "." + mybatisSqlId, tempList);
}
session.commit();
session.clearCache(); // 移动到循环结束后执行
long endTime = System.currentTimeMillis();
logger.info("批量插入数据耗时:" + (endTime - startTime) + "毫秒");
} catch (Exception e) {
logger.error("batchCommit error!", e);
if (session != null) {
session.rollback();
}
} finally {
if (session != null) {
session.close();
}
}
}
}
调用:
![](https://i-blog.csdnimg.cn/blog_migrate/8ed69a70925044d8b4f55fbc9ecae95a.png)