解决mybtis分页插件getTotal,getPage全部为0的“坑”
getRecords可以获取全部数据,但getTotal,getPage全部为0。其实不是插件本身的坑,而是忘记配合了config。(把别的项目代码迁了过来,没有迁config)注意点和问题原因已在代码中标注
@Configuration
public class MybatisPlusPageConfig {
/* 旧版本配置
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}*/
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,
* 需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
//创建拦截器,对执行的sql进行拦截
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//对Mysql拦截
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
再来看一下控制台分页查询的执行情况
JDBC Connection [HikariProxyConnection@379300548 wrapping com.mysql.cj.jdbc.ConnectionImpl@6c7fbfdb] will not be managed by Spring
==> Preparing: SELECT COUNT(*) FROM product_order WHERE (open_id = ?)
==> Parameters: o4y6G4hvJSxYp1dsm3wwNhybgsug(String)
<== Columns: COUNT(*)
<== Row: 33
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@792e6f5f]
可以看到sql语句是全量查询的,可以猜出分页流程为:全量查询-》本地分页,而如果不对查询结果进行拦截,mybatis将不能执行分页操作,自然也拿不到页数和总数的数据了。
当然,如果在查询时配置Page时将参数设置为false,也将不能正常查询,如
new Page<ProductOrderDO>(page,size,false)
Page对象的第三个参数传的是false,如果传false的话,代表不执行查询总记录数的那条sql语句。默认是true。