对于大数据量插入数据库应用场景,上万条的对象直接插入数据库会导致SQL过长报错。
所以在此封装List截取迭代工具类,将List拆分后分批次插入数据库
代码如下:
import java.util.List;
import java.util.function.Consumer;
/**
* 批量插入数据迭代类
*
* @param <T> 泛型
*/
public class BatchDDLIterator<T> {
private final List<T> list;
private final Integer ddlSize;
public BatchDDLIterator(List<T> list, Integer size) {
this.list = list;
this.ddlSize = size;
}
public void forEach(Consumer<List<T>> action) {
if (list == null || ddlSize == null || ddlSize <= 0) throw new RuntimeException("传入数据异常");
int size = list.size();
if (size > 0 && size <= ddlSize) {//如果传入的list小于ddlSize直接返回
action.accept(list);
} else {
int times = size / ddlSize + 1;//需要迭代的次数
for (int i = 0; i < times; i++) {
List<T> sonList;
if (i == times - 1) {//如果为最后一次迭代
sonList = list.subList(i * ddlSize, size);
} else {
sonList = list.subList(i * ddlSize, (i + 1) * ddlSize);
}
if (sonList.size() > 0) {
action.accept(sonList);
}
}
}
}
}
使用方法:
public static void main(String[] args) {
List<String> data=new ArrayList<>();
for (int i = 0; i < 1000; i++) {
data.add("val"+i);
}
BatchDDLIterator<String> stringBatchDDLIterator = new BatchDDLIterator<>(data, 22);
stringBatchDDLIterator.forEach(a->{
System.out.println(a);
System.out.println(a.size());
});
}