目录
1 前言
2 配置分页插件
2.1 selectPage()测试
2.2 自定义分页功能
1 前言
大家之前肯定都用过PageHelper来进行分页,其实mybatisplus中也提供了一个分页插件PaginationInnerInterceptor,其实分页的本质就是内部封装了一个拦截器,对于满足条件的数据进行过滤处理。

2 配置分页插件
相关配置:
@Configuration
//扫描mapper接口所在的包
@MapperScan("com.atguigu.mybatisplus.mapper")
public class MyBatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//添加分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}}
注意:因为PaginationInnerInterceptor支持好几种数据库类型,DbType根据类型获取应使用的分页方案。
2.1 selectPage()测试
在mapper提供的API中就有进行分页的方法selectPage,一个是Page对象,一个是Wrapper条件构造器对象。(就是将用wrapper对象筛选出符合条件的数据,然后根据page对象进行分页)
<P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);
测试语句:
@Testpublic void testPage(){Page<User> page = new Page<>(2, 3);userMapper.selectPage(page, null);System.out.println("当前页数据:"+page.getRecords());System.out.println("总分页数量:"+page.getPages());System.out.println("总记录数量:"+page.getTotal());System.out.println("是否有下一页:"+page.hasNext());System.out.println("是否有上一页:"+page.hasPrevious());}
控制台打印输出:

可以发现,我们的Page对象中的输入了两个参数,一个当前页,一个每页条数。
2.2 自定义分页功能
有时候可能mybatisplus中mapper提供的API不足以满足我们从查询要求,那么此时就需要我们自定义一个分页
mapper:
/*** 通过年龄查询用户信息并分页* @param page MyBatis-Plus所提供的分页对象,必须位于第一个参数的位置* @param age* @return*/Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
注意:mybatis-plus提供的分页对象,必须位于第一个参数的位置。
mapper.xml:
<!--Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);--><select id="selectPageVo" resultType="User">select uid,user_name,age,email from t_user where age > #{age}</select>
测试类:
@Testpublic void testPageVo(){Page<User> page = new Page<>(1, 3);userMapper.selectPageVo(page, 20);System.out.println(page.getRecords());System.out.println(page.getPages());System.out.println(page.getTotal());System.out.println(page.hasNext());System.out.println(page.hasPrevious());}
控制台sql:
==> Preparing: SELECT COUNT(*) AS total FROM t_user WHERE age > ?
==> Parameters: 20(Integer)
<== Columns: total
<== Row: 90
<== Total: 1
==> Preparing: select uid,user_name,age,email from t_user where age > ? LIMIT ?
==> Parameters: 20(Integer), 3(Long)
<== Columns: uid, user_name, age, email
<== Row: 1, ybc1, 21, null
<== Row: 2, ybc2, 22, null
<== Row: 3, ybc3, 23, null
<== Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a08078c]
[User(id=null, name=null, age=21, email=null, isDeleted=null), User(id=null, name=null, age=22, email=null, isDeleted=null), User(id=null, name=null, age=23, email=null, isDeleted=null)]
30
90
true
false
可以发现,我们在xml文件中写的sql并没有实现分页功能,而是在mapper文件中传输过来时已经帮我们实现好了。









![[一起学习pytorch吧]之torch.sign函数](https://img-blog.csdnimg.cn/20200316211101489.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pc3N5b3VkYWlzeQ==,size_16,color_FFFFFF,t_70)








