Mybatis分頁外掛PageHelper
阿新 • • 發佈:2019-01-01
1.說明
如果你也在用Mybatis,建議嘗試該分頁外掛,這個一定是最方便使用的分頁外掛。
該外掛目前支援Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種資料庫分頁。
2.使用方法
第一步:在Mybatis配置xml中配置攔截器外掛:
<plugins> <!-- com.github.pagehelper為PageHelper類所在包名 --> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- 設定資料庫型別 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種資料庫--> <property name="dialect" value="mysql"/> </plugin> </plugins>
第二步:在程式碼中使用
1、設定分頁資訊:
//獲取第1頁,10條內容,預設查詢總數count
PageHelper.startPage(1, 10);
//緊跟著的第一個select方法會被分頁
List<Country> list = countryMapper.selectIf(1);
2、取分頁資訊
//分頁後,實際返回的結果list型別是Page<E>,如果想取出分頁資訊,需要強制轉換為Page<E>, Page<Country> listCountry = (Page<Country>)list; listCountry.getTotal();
3、取分頁資訊的第二種方法
//獲取第1頁,10條內容,預設查詢總數count PageHelper.startPage(1, 10); List<Country> list = countryMapper.selectAll(); //用PageInfo對結果進行包裝 PageInfo page = new PageInfo(list); //測試PageInfo全部屬性 //PageInfo包含了非常全面的分頁屬性 assertEquals(1, page.getPageNum()); assertEquals(10, page.getPageSize()); assertEquals(1, page.getStartRow()); assertEquals(10, page.getEndRow()); assertEquals(183, page.getTotal()); assertEquals(19, page.getPages()); assertEquals(1, page.getFirstPage()); assertEquals(8, page.getLastPage()); assertEquals(true, page.isFirstPage()); assertEquals(false, page.isLastPage()); assertEquals(false, page.isHasPreviousPage()); assertEquals(true, page.isHasNextPage());
3.TestPageHelper
@Test
public void testPageHelper() {
//建立一個spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
//從spring容器中獲得Mapper的代理物件
TbItemMapper mapper = applicationContext.getBean(TbItemMapper.class);
//執行查詢,並分頁
TbItemExample example = new TbItemExample();
//分頁處理
PageHelper.startPage(2, 10);
List<TbItem> list = mapper.selectByExample(example);
//取商品列表
for (TbItem tbItem : list) {
System.out.println(tbItem.getTitle());
}
//取分頁資訊
PageInfo<TbItem> pageInfo = new PageInfo<>(list);
long total = pageInfo.getTotal();
System.out.println("共有商品:"+ total);
}