Java 8 MyBatis Plus 批量新增:分段插入 List 数据

在 Java 8 中,你可以使用 List.subList() 方法将一个 List 对象分成多个子列表。然后,你可以使用 MyBatis Plus 的批量插入方法来批量新增这些子列表,从而提高数据插入效率。

代码示例

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        // 假设 userList是要新增的用户列表

        int batchSize = 200; // 每段的大小

        int totalSize = userList.size();
        int fromIndex = 0;
        int toIndex = batchSize;

        while (fromIndex < totalSize) {
            if (toIndex > totalSize) {
                toIndex = totalSize;
            }

            List<User> subList = userList.subList(fromIndex, toIndex);
            // 使用MyBatis Plus的批量插入方法将 subList 批量新增到数据库中
            // 这里假设使用 UserMapper 来操作数据库
            // UserMapper.insertBatch(subList);

            fromIndex += batchSize;
            toIndex += batchSize;
        }
    }
}

代码解析

上面的代码使用 List.subList(fromIndex, toIndex) 方法将 User 列表分成多个大小为 batchSize 的子列表。然后,你可以使用 MyBatis Plus 的批量插入方法将每个子列表批量新增到数据库中。

注意

请注意,你需要根据你的实际情况调整代码来适应你的项目。例如,你需要根据你的数据库和 MyBatis Plus 配置选择合适的批量插入方法。

Java 8 MyBatis Plus 批量新增:分段插入 List 数据

原文地址: https://www.cveoy.top/t/topic/qdc7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录