使用pageHelper遇到的問題



在做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() {
//部門和員工一起查出來
// employeeMapper.selectByExampleWithDept(null);
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<Employee> list2 = employeeMapper.selectByExampleWithDept(null); 沒有生效,當把 employeeMapper.selectByExampleWithDept(null); 注釋后,分頁又成功了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM