使用Mybatis批量插入,分批次插入工具类实现

目录

1.背景

2.批次工具类实现SqlUtil

3.使用

1.背景

批量插入通过sql拼接插入数据,可以提高插入效率。

当数据量过大,mysql有max_allowed_packet 参数限制。

需要分批次插入,比如10000条数据,分为10次,一次插入1000条。

2.批次工具类实现SqlUtil

public class SqlUtil {

    private SqlUtil() {
    }

    /**
     * 分批次批量插入
     * @param list 全量数据
     * @param batchSize 批次插入大小
     * @param consumer 插入处理
     * @param <E>
     */
    public static <E> void batchInsert(List<E> list, int batchSize, Consumer<List<E>> consumer) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<E> insertList = Lists.newArrayList();
        int size = list.size();
        int idxLimit = Math.min(batchSize, size);
        int i = 1;
        for (Iterator<E> item = list.iterator(); item.hasNext(); ++i) {
            E element = item.next();
            insertList.add(element);
            if (i == idxLimit) {
                consumer.accept(insertList);
                insertList.clear();
                idxLimit = Math.min(idxLimit + batchSize, size);
            }
        }
    }
}

3.使用

在工具类里面使用批量插入,设置好每次插入数量。

每次插入1000条,根据公司业务可以调整。

@Service
public class UserServiceImpl {
    @Resource
    private UserMapper userMapper;
    public void batchInsert(List<UserInfo> addUserInfoList){

        SqlUtil.batchInsert(addUserInfoList, 1000, (insertList) -> {
            userMapper.batchInsert(insertList);
        });
    }
}

以下是一个简单的MyBatis批量插入数据的工具类: ``` public class BatchInsertUtil { private static final int BATCH_SIZE = 1000; public static <T> void batchInsert(List<T> dataList, SqlSession sqlSession, String statement) { if (dataList == null || dataList.isEmpty()) { return; } int size = dataList.size(); int batchCount = size % BATCH_SIZE == 0 ? size / BATCH_SIZE : size / BATCH_SIZE + 1; int startIndex, endIndex; for (int i = 0; i < batchCount; i++) { startIndex = i * BATCH_SIZE; endIndex = Math.min((i + 1) * BATCH_SIZE, size); List<T> subList = dataList.subList(startIndex, endIndex); sqlSession.insert(statement, subList); } sqlSession.flushStatements(); } } ``` 使用方法如下: ``` SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); try { BatchInsertUtil.batchInsert(dataList, sqlSession, "com.example.mapper.insertBatch"); sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); } finally { sqlSession.close(); } ``` 其中,`dataList`为待插入的数据列表,`sqlSession`为MyBatis的`SqlSession`对象,`statement`为对应的Mapper方法名称。要使用工具类,需要在Mapper文件中定义对应的批量插入方法,例如: ``` <insert id="insertBatch" parameterType="java.util.List"> insert into my_table (column1, column2, column3) values <foreach collection="list" item="item" separator=","> (#{item.column1}, #{item.column2}, #{item.column3}) </foreach> </insert> ``` 该方法使用MyBatis的`foreach`标签,将数据列表中的每一个元素都插入到数据库中。由于批量插入数据可能会造成内存溢出,因此在插入前需要将数据列表按照一定的大小为多个批次插入,本例中批次大小为1000。在插入完成后需要调用`flushStatements()`方法来刷新缓存,确保所有的语句都已经发送到数据库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值