首先看一下测试的内容和运行结果
@Test
void testGetPage(){
IPage page = new Page(2, 5);
bookDao.selectPage(page, null);
System.out.println(page.getCurrent());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.getPages());
System.out.println(page.getRecords());
}

getTotal 和 getPage 对应输出的是图中红框中的内容,为什么会出现这样的情况呢?这个主要源于 mybatisplus 内部的机制。对于 MySQL 的分页操作使用 limit 关键字进行,而并不是所有的数据库都使用 limit 关键字实现的,这个时候 mybatisplus 为了制作的兼容性强,将分页操作设置为基础查询操作的升级版。
基础操作中有查询全部的功能,而在这个基础上只需要升级一下就可以得到分页操作。所以 mybatisplus 将分页操作做成了一个开关,这个开关是通过MP的拦截器的形式存在的,具体设置如下:
@Configuration
public class MPConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
上述代码第一行是创建MP的拦截器栈,这个时候拦截器栈中没有具体的拦截器,第二行是初始化了分页拦截器,并添加到拦截器栈中。如果后期开发其他功能,需要添加全新的拦截器,按照第二行的格式继续add进去新的拦截器就可以了。
现在看一下控制台分页查询的执行情况,问题就已经解决了,这里需要注意将方法定义为一个Bean,同时将对应的类设为配置类,用注解@Configuration
