首先我们的分页是基于Interceptor的
所以我们的就得在我们的interceptor加上我们的PaginationInnerInterceptor对象:
代码实现:
@MapperScan("com.atguigu.mybatisplus.mapper")
@Configuration
public class mybatisConfig {
@Bean
public MybatisPlusInterceptor MPI(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
}
②、我们实现分页功能。使用的是继承于BaseMapper接口的UserMapper接口的selectPage方法。调用该方法我们必须传入两个参数:
1、第一个是Ipage接口的实现类。根据继承关系我们可以知道:

其Page就是一个Ipage实现类.
2、第二个参数就是包装类Wrapper,可以传入null
代码实现:
@Autowired
UserMapper userMapper;
@DisplayName("pageTest")
@Test
public void test01(){
Page<User> page = new Page<>(1,3);
//新建一个Page对象,泛型为我们操作的类。User1表示的是当前页码,3则是pageSize
Page<User> userPage1 = userMapper.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.hasPrevious());
System.out.println("是否有下一页:"+page.hasNext());
// System.out.println(userPage1);
}
二、自定义分页功能:
首先我们需要在我们的UserMapper中定义我们的我们抽象方法,
该方法返回Page对象:
Page<User> definePageVo(@Param("page") Page<User> page,@Param("age") int age))
然后在我们userMapper.xml中配置我们自定义的的方法:
<select id="selectPageVo" resultType="com.atguigu.mybatisplus.bean.User">
SELECT id,name,age,email from user where age >#{age}
</select>
测试:
@Test
public void test02(){
// 注入我们的参数
Page<User> userPage = new Page<>(2, 3);
userMapper.selectPageVo(userPage, 23);
// 获取结果:
System.out.println(userPage.getCurrent());
}
即可
本文介绍了如何在Spring Boot项目中利用MyBatisPlus实现分页功能,包括基于Interceptor的默认分页配置和自定义分页查询。通过在mybatisConfig配置类中添加PaginationInnerInterceptor,并在Mapper接口中使用selectPage方法实现基础分页。同时,展示了如何自定义分页查询方法,通过在Mapper接口定义新的方法并在XML文件中配置SQL,完成自定义分页需求。
648

被折叠的 条评论
为什么被折叠?



