Skip to content

Instantly share code, notes, and snippets.

@codethereforam
Last active February 19, 2021 17:30
Show Gist options
  • Save codethereforam/278d48d63909462727e29e9cfea240ff to your computer and use it in GitHub Desktop.
Save codethereforam/278d48d63909462727e29e9cfea240ff to your computer and use it in GitHub Desktop.
分批查询工具类
/**
* 分批查询
*
* <p>
* sql中copy以下代码:
* <pre>{@code
* <if test="begin != null and pageSize != null">
* limit #{begin}, #{pageSize}
* </if>
* }</pre>
*
* @param batchQueryListFunction mapper查询方法
* @param paramMap paramMap 查询参数map
* @param pageSize pageSize 每批次大小
* @return 查询结果合集
*/
public static <E> List<E> batchQuery(Function<Map<String, Object>, List<E>> batchQueryListFunction, Map<String, Object> paramMap, int pageSize) {
List<E> allList = new ArrayList<>();
int page = 0;
HashMap<String, Object> newParamMap;
if (paramMap == null) {
newParamMap = new HashMap<>(2);
} else {
newParamMap = new HashMap<>(paramMap);
}
newParamMap.put("pageSize", pageSize);
for (; ; ) {
newParamMap.put("begin", page * pageSize);
List<E> splitList = batchQueryListFunction.apply(newParamMap);
// 第一次查询结果为空
if (page == 0 && CollectionUtils.isEmpty(splitList)) {
return Collections.emptyList();
}
if (CollectionUtils.isNotEmpty(splitList)) {
allList.addAll(splitList);
}
if (splitList.size() < pageSize) {
break;
}
page++;
}
return allList;
}
/**
* 分批查询;默认每批次查500
*
* <p>
* sql中copy以下代码:
* <pre>{@code
* <if test="begin != null and pageSize != null">
* limit #{begin}, #{pageSize}
* </if>
* }</pre>
*
* @param batchQueryListFunction mapper查询方法
* @param paramMap paramMap 查询参数map
* @return 查询结果合集
*/
public static <E> List<E> batchQuery(Function<Map<String, Object>, List<E>> batchQueryListFunction, Map<String, Object> paramMap) {
return batchQuery(batchQueryListFunction, paramMap, 500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment