在使用saveAll()等方法时,为了防止集合元素过大,使用splitList将原集合,分割成若干个小集合
java
import java.util.ArrayList;
import java.util.List;
public class ListUtils {
/**
* 将集合拆分成若干个batch,并将batch存于新的集合
*
* @param list 目标集合
* @param size batch大小
* List m: [a, b, c, d, e, f, g]
* -> splitList(m, 3)
* -> [[a, b, c], [d, e, f], [g]]
* @return List<Batch>
*/
public static <T> List<List<T>> splitList(List<T> list, int size) {
//集合为空时,返回null
if (list == null){
return null;
}
//分割后的集合套集合
List<List<T>> l1 = new ArrayList<>();
//如果分割size>=集合size,那就没必要分割
if (list.size() <= size){
l1.add(list);
} else {
//集合size
int s = list.size();
//x=新的集合套集合的size
int x = s / size;
//y=新的集合套集合最后一个子集合的size
int y = s % size;
if (y != 0){
x = x + 1;
}
int index = 0;
for (int i = 0; i < x; i++) {
List<T> l2 = new ArrayList<>();
for (int j = 0; j < list.size(); j++) {
//按原集合给subList装元素,
l2.add(list.get(index));
index++;
//当达到sublist个数size装满时,跳出循环
if (l2.size() == size) {
l1.add(l2);
break;
//最后一个subList时
} else if (x == l1.size() + 1 && y == l2.size()) {
l1.add(l2);
break;
}
}
}
}
return l1;
}
}
数据库批处理操作
java
if (bigList.size() > 0) {
for (List<CustomTableBean> subList : ListUtils.splitList(bigList, 100)) {
int rows = customMapper.insertAll(subList);
log.info("insert data size is " + rows);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
log.error(e.printStackTrace(););
}
}
}