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='[email protected]', age=18}
stu = Student实体:{
    
    id=2, name='李四', email='[email protected]', age=26}
stu = Student实体:{
    
    id=3, name='王五', email='[email protected]', 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.

猜你喜欢

转载自blog.csdn.net/lln1540295459/article/details/121057467