Mybatis分页插件PageHelper的使用
PageHelper分页的实现利用了自定义拦截器实现了Mybatis拦截器接口。
1、pom.xml中引入pageHelper分页jar包
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.11</version> </dependency>
2、spring配置文件中配置分页插件
<!-- 把交给IOC管理 SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--配置mybatis 插件--> <property name="plugins"> <set> <!--配置pageHelper 分页插件--> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <props> <!--方言:--> <prop key="helperDialect">oracle</prop> </props> </property> </bean> </set> </property> </bean>
3、部分junit测试代码
@Autowired private EmployeeService employeeService; @Test public void testPageHelper() { // 设置分页查询 PageHelper.startPage(1, 3); List<Employee> empList = employeeService.getEmpByPage(); for (Employee employee: empList) { System.out.println(employee); } // 此处输出的结果调用的PageHelper分页插件中Page类中重写的toString方法,其中Page类继承自ArrayList System.out.println(empList); PageInfo pageInfo = new PageInfo(empList); System.out.println(pageInfo); }
其中需要注意的是Page类继承自ArrayList,其中重写了toString()方法
重写的toString()方法
public String toString() { return "Page{count=" + this.count + ", pageNum=" + this.pageNum + ", pageSize=" + this.pageSize + ", startRow=" + this.startRow + ", endRow=" + this.endRow + ", total=" + this.total + ", pages=" + this.pages + ", reasonable=" + this.reasonable + ", pageSizeZero=" + this.pageSizeZero + '}' + super.toString(); }
例如上面junit测试代码中
System.out.println(empList)打印的结果如下
Page{count=true, pageNum=1, pageSize=3, startRow=0, endRow=3, total=14, pages=5, reasonable=false, pageSizeZero=false}[Employee{empno=7369, ename=SMITH, job=CLERK, mgr=7902, hiredate=Wed Dec 17 00:00:00 GMT+08:00 1980, sal=800.0, comm=0, deptno=20}, Employee{empno=7499, ename=ALLEN, job=SALESMAN, mgr=7698, hiredate=Fri Feb 20 00:00:00 GMT+08:00 1981, sal=1600.0, comm=300, deptno=30}, Employee{empno=7521, ename=WARD, job=SALESMAN, mgr=7698, hiredate=Sun Feb 22 00:00:00 GMT+08:00 1981, sal=1250.0, comm=500, deptno=30}]
PageInfo封装了结果集。如果需要取数据,可以利用该类中的对应方法。