|
在做SSM整合的时候,遇到一个小问题,在我使用pageHelper的时候,分页的效果总是无法正确显示,卡了我几个小时,现在来说一下我的问题。
1.首先导入pageHelper的包:
<!--引入pageHelper分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
2.在mybatis-config.xml配置:
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--分页参数合理化 -->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
3.接下来开始测试:
测试代码:
@Test
public void getAll(){
PageHelper.startPage(1,5);
List<Employee> list2 = employeeService.getAll();
PageInfo<Employee> pi = new PageInfo<>(list2);
System.out.println("当前页码:"+pi.getPageNum());
System.out.println("总页码:"+pi.getPages());
System.out.println("总记录数:"+pi.getTotal());
}
测试结果:

发现结果并不是我所需要的,结果并没有分页,于是我在mapper层继续测试:
测试代码:
@Test
public void getAll(){
PageHelper.startPage(1,5);
List<Employee> list2 = employeeMapper.selectByExampleWithDept(null);
PageInfo<Employee> pi = new PageInfo<>(list2);
System.out.println("当前页码:"+pi.getPageNum());
System.out.println("总页码:"+pi.getPages());
System.out.println("总记录数:"+pi.getTotal());
}
测试结果:

结果正是我所需要的,既然mapper层没错,那么程序的问题就是service层出错了,service层代码如下:
public List<Employee> getAll() {
employeeMapper.selectByExampleWithDept(null);
return employeeMapper.selectByExampleWithDept(null);
}
我们可以发现,查询代码我查了两次,这就是导致我无法分页成功,于是我把 employeeMapper.selectByExampleWithDept(null) 注释掉,再次查询就成功了
public List<Employee> getAll() {
return employeeMapper.selectByExampleWithDept(null);
}
4.总结一下使用pageHelper的注意点:
- **PageHelper.startPage(1,5)**要放在查询语句的前面
- **PageHelper.startPage(1,10)**只对该语句以后的第一个查询语句得到的数据进行分页,如果有两条查询语句,只对第一条查询语句生效,也就是 employeeMapper.selectByExampleWithDept(null) 这条有效,而 employeeMapper.selectByExampleWithDept(null) 没有生效,虽然查询出了所有数据,但是分页无效
再次做一个测试:
@Test
public void getAll(){
PageHelper.startPage(1,5);
employeeMapper.selectByExampleWithDept(null);
List<Employee> list2 = employeeMapper.selectByExampleWithDept(null);
PageInfo<Employee> pi = new PageInfo<>(list2);
System.out.println("当前页码:"+pi.getPageNum());
System.out.println("总页码:"+pi.getPages());
System.out.println("总记录数:"+pi.getTotal());
}
结果:

查询结果没有分页,也就是PageHelper.startPage(1,5) 对employeeMapper.selectByExampleWithDept(null)生效,而List list2 = employeeMapper.selectByExampleWithDept(null)没有生效,当把employeeMapper.selectByExampleWithDept(null) 注释后,分页又成功了 |