java8 将list 分段 每段大小200 mybatisplus 批量新增
在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的批量插入方法将每个子列表批量新增到数据库中。
请注意,你需要根据你的实际情况调整代码来适应你的项目
原文地址: https://www.cveoy.top/t/topic/ivGn 著作权归作者所有。请勿转载和采集!