小書MybatisPlus第4篇-表格分頁與下拉分頁查詢
- 2020 年 7 月 15 日
- 筆記
本文為mybatis系列文檔的第4篇,前三篇請訪問下面的網址。
一、讓Spring Boot-MybatisPlus支援分頁
在已經集成了Mybatis Plus的Spring項目中加入如下分頁攔截器的配置,讓MybatisPlus支援分頁
@Configuration
public class MybatisPlusConfiguration {
//配置分頁攔截器
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
二、單表查詢分頁-表格分頁
@Test
public void testSelect() {
LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
query.ge(User::getAge,10) //查詢條件:年齡大於10
.orderByDesc(User::getAge); //按照年齡的倒序排序
Page<User> page = new Page<> (1,10); //查詢第1頁,每頁10條數據
userMapper.selectPage(page,query); //page分頁資訊,query查詢條件
System.out.println("總頁數:"+ page.getPages());
System.out.println("總記錄數:"+ page.getTotal());
// 分頁返回的對象與傳入的對象是同一個
List<User> list = page.getRecords();
list.forEach(System.out::println);
}
查詢輸出結果如下:
總頁數:1
總記錄數:6
User(id=3, name=Tom, age=28, [email protected])
User(id=5, name=Billie, age=24, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=1, name=Jone, age=18, [email protected])
User(id=1280261858003038209, name=字母哥, age=18, email=null)
在分頁查詢過程中,一共執行了兩條SQL
# 第一條SQL用於查詢在query條件下的總條數
SELECT COUNT(1) FROM user WHERE age >= ?
# 第二條SQL用於查詢具體的數據
SELECT id,name,age,email
FROM user
WHERE age >= ?
ORDER BY age DESC
LIMIT ?,?
這種分頁方式比較適合於傳統應用中,表格分頁的開發。需要給出總條數,以及每頁多少條。
三、不查詢總記錄數的分頁-下拉分頁
在一些現代的互聯網資訊網站,或者應用app。通常不會給出數據的總條數,而是通過滑鼠或者手勢,每次下拉都載入n條數據。
這種情況下的分頁通常就不需要查詢總條數了,如果查詢總條數浪費資料庫的計算資源,使響應時間變長。所以我們應該只做分頁數據查詢,不查詢總條數。設置page分頁的第三個參數為false。
輸出結果總頁數和總條數都是0,但是分頁數據正常查詢回來了。
總頁數:0
總記錄數:0
User(id=3, name=Tom, age=28, [email protected])
User(id=5, name=Billie, age=24, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=1, name=Jone, age=18, [email protected])
User(id=1280261858003038209, name=字母哥, age=18, email=null)
只執行了這樣一個SQL
ELECT id,name,age,email
FROM user
WHERE age >= ?
ORDER BY age DESC
LIMIT ?,?
歡迎關注我的部落格,裡面有很多精品合集
- 本文轉載註明出處(必須帶連接,不能只轉文字):字母哥部落格。
覺得對您有幫助的話,幫我點贊、分享!您的支援是我不竭的創作動力! 。另外,筆者最近一段時間輸出了如下的精品內容,期待您的關注。
- 《手摸手教你學Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《實戰前後端分離RBAC許可權管理系統》
- 《實戰SpringCloud微服務從青銅到王者》
- 《VUE深入淺出系列》