一、pagehelper分页插件
pagehelper是一个开源的基于Mybatis拦截器开发的通用分页插件工具,一般项目中也是使用这个。
具体的项目地址:https://github.com/pagehelper/Mybatis-PageHelper
具体的使用说明:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md
注意:该插件是中国人开发的,文档是中文的。
二、使用步骤:
1.引入依赖:
maven坐标:
1
2
3
4
5<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.11</version> </dependency>
建议使用最新版本。
2.在Mybatis中注册该插件,并设置默认值
1
2
3
4<plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 合理分页 --> <property name="reasonable" value="true"/> </plugin>
一般只设置一个reasonable(是否合理分页)为true,其它参数请参考具体文档。
3.使用代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37public class MybatisTest { private SqlSessionFactory sqlSessionFactory; @Before public void init() throws IOException { String resource = "mybatis-config.xml"; //1.使用mybatis的工具读取配置文件 InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //2.创建sqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); inputStream.close(); } /** * 测试分页 */ @Test public void testPage() { SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //分页 Page<Object> page = PageHelper.startPage(1, 2); //设置查询总数 page.setCount(true); //设置排序字段 page.setOrderBy("id desc"); List<User> users = userMapper.selectList(); System.out.println(users); //获取总数查询结果 long count = page.getTotal(); System.out.println("查询总数:"+count); sqlSession.close(); } }
说明:
1.主要通过PageHelper的startPage方法设置要查询的分页(从1开始),该方法会返回一个Page,通过设置该Page的属性可以进行分页、排序、以及总数查询.
2.只能通过设置PageHelper的startPage方法返回的Page才能使插件生效。
三、补充说明
1.该插件的使用非常简单,只需要通过静态方法设置好对应属性即可,不需要在mapper映射文件中写limit和order by,该插件会自动添加。
2.如果要查询总数,总数结果只能通过返回的Page对象获取。
3.如果存在多个mapper接口调用,则只会对第一个mapper生效,因为使用之后会马上清理。
4.该插件不适用于返回嵌套结果集的多表查询,因为Mybatis会合并其结果,导致分页数量不准确。
最后
以上就是冷艳路人最近收集整理的关于Mybatis从入门到精通——分页插件pagehelper的使用(20)一、pagehelper分页插件二、使用步骤:三、补充说明的全部内容,更多相关Mybatis从入门到精通——分页插件pagehelper内容请搜索靠谱客的其他文章。
发表评论 取消回复