Java -- MyBatis学习笔记11、PageHelper

1、Mybatis通用分页插件

  • github地址:

https://github.com/pagehelper/Mybatis-PageHelper

PageHelper支持多种数据库:

  • Oracle
  • Mysql
  • MariaDB
  • SQLite
  • Hsqldb
  • 等等。。。

2、基于PageHelper分页

  • 在pom文件中加入maven坐标:
<dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
</dependency>
  • 在主配置文件中的<environments>加入plugin配置:
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>

2.1、PageHelper对象

查询语句之前调用PageHelper.startPage静态方法。在你需要进行分页的MyBatis查询方法前调用PageHelper.startPage静态方法即可,紧跟在这个方法后的第一个 MyBatis 查询方法会被进行分页。

  • 在方法里边使用PageHelper.startPage
@Test
    public void selectAll()
    {
        //获取第 1 页,3 条内容
        PageHelper.startPage(1,3);
        List<UserInfo> userList = userInfoDao.selectAll();
        //循环输出集合中的结果
        userList.forEach(x -> System.out.println(x));
    }
  • 查看日志:
==>  Preparing: SELECT count(0) FROM UserInfo 
==> Parameters: 
<==    Columns: count(0)
<==        Row: 9
<==      Total: 1
==>  Preparing: select * from UserInfo LIMIT ? 
==> Parameters: 3(Integer)
<==    Columns: id, Name, Age
<==        Row: 3, 王五, 16
<==        Row: 5, 张飞, 15
<==        Row: 7, 刘备, 18
<==      Total: 3

可以看到、先查询一共有9条记录、再分页、只显示3条数据。

原文地址:https://www.cnblogs.com/dcy521/p/14749190.html