mybatis 分頁外掛PageHelper的簡單使用
阿新 • • 發佈:2018-12-05
分頁方式的分類:
- 邏輯分頁
- 物理分頁
MyBatis-PageHelper 的使用:
-
首先在pom.xml配置檔案中增加相關的外掛。
<dependency> 2 <groupId>com.github.pagehelper</groupId> 3 <artifactId>pagehelper</artifactId> 4<version>5.1.7</version> 5 </dependency>
新建一個mybatis-config.xml 的檔案:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3 4 <configuration> 5<settings> 6 <!-- 使用jdbc的getGeneratedKeys獲取資料庫自增主鍵值 --> 7 <setting name="useGeneratedKeys" value="true" /> 8 <!-- 使用列別名替換列名 預設:true --> 9 <setting name="useColumnLabel" value="true" /> 10 <!-- 開啟駝峰命名轉換:Table {create_time} -> Entity {createTime}--> 11 <setting name="mapUnderscoreToCamelCase" value="true" /> 12 </settings> 13 <!--配置分頁外掛--> 14 <plugins> 15 <plugin interceptor="com.github.pagehelper.PageInterceptor" /> 16 </plugins> 17 18 </configuration>
載入mybatis-config.xml檔案。
呼叫:
呼叫PageHelper外掛的方法,它只會對下面的一行程式碼起作用。
第一個引數是頁數,第二個引數是條數,簡單來說就是每一頁有幾條資料。
1、這是一種物理分頁(就是直接通過SQL進行在資料庫中直接分頁,得到的資料就是我們想要分頁之後的資料),假設你使用的是mysql資料庫,在執行查詢語氣的時候,它會自動的在sql語法後面加 limit
物理分頁:記憶體開銷比較小,在資料量比較小的情況下效率比邏輯分頁還是低,在資料量很大的情況下,建議使用物理分頁
測試:
select 語法:
測試類:
打印出來的日誌:
(通過日誌,第4行,我們可以看出,當我們使用PageHelper.startPage這種物理方法的時候,它是自動在我呼叫的select後面加上了limit進行了分頁查詢)
1 09:05:37.911 [main] DEBUG com.oukele.dao.CommodityMapper.selectAll_COUNT - ==> Preparing: SELECT count(0) FROM commodity c LEFT JOIN stock s ON c.stock_id = s.stock_id LEFT JOIN commodity_company cp ON c.commodity_company_id = cp.commodity_company_id 2 09:05:37.943 [main] DEBUG com.oukele.dao.CommodityMapper.selectAll_COUNT - ==> Parameters: 3 09:05:38.142 [main] DEBUG com.oukele.dao.CommodityMapper.selectAll_COUNT - <== Total: 1 4 09:05:38.145 [main] DEBUG com.oukele.dao.CommodityMapper.selectAll - ==> Preparing: select * from commodity c left join stock s on c.stock_id = s.stock_id left join commodity_company cp on c.commodity_company_id=cp.commodity_company_id LIMIT ? 5 09:05:38.146 [main] DEBUG com.oukele.dao.CommodityMapper.selectAll - ==> Parameters: 3(Integer) 6 09:05:38.230 [main] DEBUG com.oukele.dao.CommodityMapper.selectAll - <== Total: 3