问题场景:
Inter pageNo = 5;
Inter pageSize = 10;
Page<String> page = new Page<>(pageNo,pageSize);
当数据总数小于40的时候;数据库查询返回的数据为空。
即:total/pageSize = 40/10 = 4(页数) < 5(要访问的页)
这样很不友好,相当于bug。
解决方案:
强大的mybatis-plus对这个问题已经有处理方案了。在mybatis配置bean中:
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
paginationInnerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
}
其中的paginationInnerInterceptor.setOverflow(true) 这个就是针对此问题的解决方案,意思就是-溢出总页数的时候默认是跳到第一页。
源码分析:
类com/baomidou/mybatisplus/extension/plugins/inner/PaginationInnerInterceptor.java
* count 查询之后,是否继续执行分页
*
* @param page 分页对象
* @return 是否
*/
protected boolean continuePage(IPage<?> page) {
if (page.getTotal() <= 0) {
return false;
}
if (page.getCurrent() > page.getPages()) {
if (overflow) {
//溢出总页数处理
handlerOverflow(page);
} else {
// 超过最大范围,未设置溢出逻辑中断 list 执行
return false;
}
}
return true;
}
protected void handlerOverflow(IPage<?> page) {
page.setCurrent(1);
}
从上面源码中可以看出,如果溢出总页数的时候默认是跳到第一页。