package org.sxkj.common.query;
|
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import org.springframework.util.CollectionUtils;
|
|
import java.util.List;
|
import java.util.function.Consumer;
|
import java.util.function.Function;
|
|
/**
|
* 分页处理工具类
|
*/
|
public class PaginationUtils {
|
|
/**
|
* 通用分页处理方法
|
* @param mapper MyBatis-Plus Mapper接口
|
* @param pageSize 每页大小
|
* @param queryWrapperBuilder 查询条件构建函数
|
* @param pageDataProcessor 每页数据处理函数
|
* @param <T> 实体类型
|
* @param <M> Mapper类型
|
*/
|
public static <T, M extends BaseMapper<T>> void processInPages(
|
M mapper,
|
int pageSize,
|
Function<Integer, Wrapper<T>> queryWrapperBuilder,
|
Consumer<Page<T>> pageDataProcessor) {
|
|
int currentPage = 1;
|
boolean hasNext = true;
|
|
while (hasNext) {
|
// 创建分页对象
|
Page<T> page = new Page<>(currentPage, pageSize);
|
|
// 构建当前页的查询条件
|
Wrapper<T> wrapper = queryWrapperBuilder.apply(currentPage);
|
|
// 执行分页查询
|
Page<T> resultPage = mapper.selectPage(page, wrapper);
|
List<T> records = resultPage.getRecords();
|
|
// 处理当前页数据
|
if (!CollectionUtils.isEmpty(records)) {
|
pageDataProcessor.accept(resultPage);
|
}
|
|
// 判断是否还有下一页
|
hasNext = currentPage < resultPage.getPages() && !CollectionUtils.isEmpty(records);
|
currentPage++;
|
}
|
}
|
|
/**
|
* 简化版分页处理(不需要当前页码构建查询条件)
|
* @param mapper MyBatis-Plus Mapper接口
|
* @param pageSize 每页大小
|
* @param queryWrapper 固定查询条件
|
* @param pageDataProcessor 每页数据处理函数
|
* @param <T> 实体类型
|
* @param <M> Mapper类型
|
*/
|
public static <T, M extends BaseMapper<T>> void processInPages(
|
M mapper,
|
int pageSize,
|
Wrapper<T> queryWrapper,
|
Consumer<Page<T>> pageDataProcessor) {
|
|
processInPages(mapper, pageSize, page -> queryWrapper, pageDataProcessor);
|
}
|
}
|