Mybatis 通用分页插件PageHelper

Mybatis 通用分页插件

PageHelper

基于 PageHelper 分页

实现步骤:

1.maven坐标

<dependency>
 <groupId>com.github.pagehelper</groupId>
 <artifactId>pagehelper</artifactId>
 <version>5.1.10</version>
</dependency>

2.加入 plugin 配置

在<environments>之前加入
<plugins>
 <plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>

3.PageHelper 对象

查询语句之前调用 PageHelper.startPage 静态方法。

除了 PageHelper.startPage 方法外,还提供了类似用法的 PageHelper.offsetPage 方法。
在你需要进行分页的 MyBatis 查询方法前调用 PageHelper.startPage 静态方法即可,紧跟在这个方法后的第一个 MyBatis 查询方法会被进行分页。

@Test
public void testSelect() throws IOException {
//获取第 1 页,3 条内容
PageHelper.startPage(1,3);
 List<Student> studentList = studentDao.selectStudents();
 studentList.forEach( stu -> System.out.println(stu));
}

使用PageHelper

接口方法:

    List<Student> selectAllStudents();

mapper文件:

    <select id="selectAllStudents" resultType="com.lln.vo.Student">
        select * from student order by id
    </select>

测试类:

    @Test
    public void testSelectAllStudents(){
        //1.获取SqlSession
        SqlSession session = MyBatisUtil.getSqlSession();
        //2.获取dao的代理
        StudentDao dao = session.getMapper(StudentDao.class);
        //调用PageHelper的方法
        PageHelper.startPage(1,3);
        List<Student> students = dao.selectAllStudents();
        students.forEach(stu -> System.out.println("stu = "+stu));
        //3.关闭SqlSession对象
        session.close();
    }

运行结果:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Created connection 209833425.
Returned connection 209833425 to pool.
Cache Hit Ratio [SQL_CACHE]: 0.0
Opening JDBC Connection
Checked out connection 209833425 from pool.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@c81cdd1]
==>  Preparing: SELECT count(0) FROM student 
==> Parameters: 
<==    Columns: count(0)
<==        Row: 7
<==      Total: 1
==>  Preparing: select * from student order by id LIMIT ? 
==> Parameters: 3(Integer)
<==    Columns: id, name, email, age
<==        Row: 1, 张三, 123@163.com, 18
<==        Row: 2, 李四, 456@163.com, 26
<==        Row: 3, 王五, 789@163.com, 30
<==      Total: 3
stu = Student实体:{id=1, name='张三', email='123@163.com', age=18}
stu = Student实体:{id=2, name='李四', email='456@163.com', age=26}
stu = Student实体:{id=3, name='王五', email='789@163.com', age=30}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@c81cdd1]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@c81cdd1]
Returned connection 209833425 to pool.
上一篇:面向对象


下一篇:C++40个入门知识点_20_ 构造函数的调用