1、遇到问题:
分页查询接口,在特殊场景下,要求不分页,返回全部数据。mp默认当size=-1时,会返回全部数据,但是total为0;当size=0时,total有值,但是没数据。没法在返回全部数据的同时,total也有值。
2、解决方法:
自定义分页拦截器,重写拦截器中的handlerLimit方法,巧妙规避当size=0,total有值list无值问题
// 自定义分页拦截器
public class CustomPaginationInnerInterceptor extends PaginationInnerInterceptor {
public CustomPaginationInnerInterceptor(DbType dbType) {
super(dbType);
}
@Override
protected void handlerLimit(IPage<?> page) {
// 此时,mp已完成对total的查询,将total设置成size值,完成对数据的查询
final long size = page.getSize();
if (size == 0) {
page.setSize(page.getTotal());
}
super.handlerLimit(page);
}
}
// mybatis-plus分页插件
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
CustomPaginationInnerInterceptor pageInterceptor = new CustomPaginationInnerInterceptor(DbType.POSTGRE_SQL);
pageInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(pageInterceptor);
return interceptor;
}
}