问题来源
对于数据库操作,不可避免会出现大数据插入的场景,而对于数据库而言
1、一次插入数据过多,sql 语句过长会报错
2、一次插入数据过多,导致长事务,不利于并发操作。
因此,需要一个将数据批量插入的工具类类辅助。那么,如果实现一个通用的工具类,你不妨可以思考下。
解决办法
利用 java8 的 Function 可以做得非常简洁通用
public class BatchUtils {
/**
* 批量执行
*
* @param datas
* @param function
* @param <T>
* @return
*/
public static <T> int batchExec(List<T> datas, Function<List<T>, Integer> function) {
return batchExec(datas, 500, function);
}
/**
* 批量执行
*
* @param datas
* @param batchSize
* @param function
* @param <T>
* @return
*/
public static <T> int batchExec(List<T> datas, int batchSize, Function<List<T>, Integer> function) {
int count = 0;
int size = datas.size();
for (int index = 0; index < size; index += batchSize) {
if (index + batchSize <= datas.size()) {
count += function.apply(datas.subList(index, index + batchSize));
} else {
count += function.apply(datas.subList(index, size));
}
}
return count;
}
public static void main(String[] args) {
List<Integer> datas = new ArrayList();
for (int i = 0; i < 100; i++) {
datas.add(i);
}
System.out.println(batchExec(datas, 10, (item) -> item.size()));;
System.out.println(batchExec(datas, 9, (item) -> item.size()));;
System.out.println(batchExec(datas, 15, (item) -> item.size()));;
}
}
总结
实现是不是很简单通用呢?如果你有更好的办法,欢迎留言讨论