1.使用maven導入jar包
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency>
2.在mybatis-config.xml
中添加如下配置:
<!-- 配置分頁插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> </plugin> </plugins>
分頁插件版本不同,interceptor 可能會有區別,配置方式根據實際情況配置參數
3.Service層 使用分頁插件
Page page = PageHelper.startPage(pageNum,sizeNum,count); List<MainSearchVo> mainSearchVoList = companyMainPageMapper.getMainSearch(fname);
參數詳解:
pageNum:當前頁
sizeNum:每頁顯示條數
count :是否查詢總條數 (true:查詢 ,false:不查詢)
獲取總頁數: page.getPages()
4.什么時候會導致不安全的分頁?
PageHelper 方法使用了靜態的 ThreadLocal 參數,分頁參數和線程是綁定的。 只要你可以保證在 PageHelper 方法調用后緊跟 MyBatis 查詢方法,這就是安全的。因為 PageHelper 在 finally 代碼段中自動清除了 ThreadLocal 存儲的對象。 如果代碼在進入 Executor 前發生異常,就會導致線程不可用,這屬於人為的 Bug(例如接口方法和 XML 中的不匹配,導致找不到 MappedStatement 時), 這種情況由於線程不可用,也不會導致 ThreadLocal 參數被錯誤的使用。 但是如果你寫出下面這樣的代碼,就是不安全的用法: PageHelper.startPage(1, 10); List<Country> list; if(param1 != null){ list = countryMapper.selectIf(param1); } else { list = new ArrayList<Country>(); } 這種情況下由於 param1 存在 null 的情況,就會導致 PageHelper 生產了一個分頁參數,但是沒有被消費,這個參數就會一直保留在這個線程上。當這個線程再次被使用時,就可能導致不該分頁的方法去消費這個分頁參數,這就產生了莫名其妙的分頁。 上面這個代碼,應該寫成下面這個樣子: List<Country> list; if(param1 != null){ PageHelper.startPage(1, 10); list = countryMapper.selectIf(param1); } else { list = new ArrayList<Country>(); } 這種寫法就能保證安全。