mybatis快速批量插入工具类

发布时间:2023年12月28日

代码示例:

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://blog.csdn.net/XikYu/article/details/135269892
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。