最近在做一个管理后台的项目,有很多分页查询,Mybatis Plus提供了非常优秀的分页插件,但是当查询页码大于最大页码的时候,就会出现结果空白。
经过查阅官方文档,发现可以在定义MybatisPlusInterceptor拦截器的时候,
PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
paginationrInterceptor.setOverflow(true);
但是这样产生的效果是溢出后按照第一页查询,而笔者现想要在页码溢出时展示最后一页。
之前在很长一度按时间内,因为我做的项目不会这么多的使用分页,所以一直都是手动的判断页码是否溢出,如果溢出就将page的当前页码设置为查询得到的页面数量,再次进行查询。分页用的少还好,一旦像是现在这个项目这样大量的用到分页,就比较头疼了,所以,今天便打算自己封装一个Helper类。
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
public class GetPageHelper<T, M extends BaseMapper<T>> {
/**
* 获取分页数据
* @param currentPage 当前页
* @param pageSize 每页数量
* @param t 实体类
* @param m mapper
* @param queryWrapper 查询条件
* @param overflow 溢出处理方式
* @return 分页数据
*/
public IPage<T> getPage(int currentPage, int pageSize, T t, M m, QueryWrapper<T> queryWrapper, boolean overflow) {
IPage<T> page = new Page<T>(currentPage, pageSize);
m.selectPage(page, queryWrapper);
if (page.getPages() < currentPage) {
if (overflow) {
page.setCurrent(1); // overflow为true的话,溢出则会查询第一页的内容
} else {
page.setCurrent(page.getPages()); //否则查询最后一页
}
m.selectPage(page, queryWrapper);
}
return page;
}
}
在此发表博客,希望能够帮助到需要的小伙伴。也作为自己学习过程中的备忘。