上一節,簡單講述了 mybatis-plus 搭建與使用入門,這一節,簡單講一下如何使用 mp 實現多表分頁。
分析
使用的工程,依舊是 spring-boot,關于分頁,官網給出了一個單表的demo,其實多表分頁實現原理相同,都是通過 mybatis 的攔截器
(攔截器做了什么?他會在你的 sql 執行之前,為你做一些事情,例如分頁,我們使用了 mp 不用關心 limit,攔截器為我們拼接。我們也不用關心總條數,攔截器獲取到我們 sql 后,拼接 select count(*)
為我們查詢總條數,添加到參數對象中)。
實現
1. 配置攔截器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@enabletransactionmanagement @configuration @mapperscan ( "com.web.member.mapper" ) public class mybatisplusconfig { /** * mybatis-plus sql執行效率插件【生產環境可以關閉】 */ @bean public performanceinterceptor performanceinterceptor() { return new performanceinterceptor(); } /* * 分頁插件,自動識別數據庫類型 多租戶,請參考官網【插件擴展】 */ @bean public paginationinterceptor paginationinterceptor() { return new paginationinterceptor(); } } |
2. mapper 接口以及 xml
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * <p> * 用戶表 mapper 接口 * </p> * * @author 殷天文 * @since 2018-06-01 */ public interface usermapper extends basemapper<user> { list<userlistmodel> selectuserlistpage(pagination page , @param ( "user" ) userlistbean user); } |
這里要注意的是,這個 pagination page 是必須要有的,否則 mp 無法為你實現分頁。
1
2
3
4
5
6
7
8
9
10
11
|
<select id= "selectuserlistpage" resulttype= "com.web.member.model.userlistmodel" > select * from ftms_user u left join ftms_user_level l on u.level_id = l.id where 1 = 1 < if test= "user.nickname != null" > and u.nickname like "%" #{user.nickname} "%" </ if > </select> |
3. service 實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import com.web.member.beans.admin.userlistbean; import com.web.member.entity.user; import com.web.member.mapper.usermapper; import com.web.member.model.userlistmodel; import com.web.member.service.userservice; import com.baomidou.mybatisplus.plugins.page; import com.baomidou.mybatisplus.service.impl.serviceimpl; import org.springframework.stereotype.service; import org.springframework.transaction.annotation.transactional; /** * <p> * 用戶表 服務實現類 * </p> * * @author 殷天文 * @since 2018-06-01 */ @service public class userserviceimpl extends serviceimpl<usermapper, user> implements userservice { @transactional (readonly= true ) @override public page<userlistmodel> selectuserlistpage(userlistbean user) { page<userlistmodel> page = new page<>(user.getcurr(), user.getnums()); // 當前頁,總條數 構造 page 對象 return page.setrecords( this .basemapper.selectuserlistpage(page, user)); } } |
最后將結果集 set 到 page 對象中,page 對象的 json 結構如下
1
2
3
4
5
6
7
8
9
10
11
12
|
{ "total" : 48 , //總記錄 "size" : 10 , //每頁顯示多少條 "current" : 1 , //當前頁 "records" : [ //結果集 數組 {...}, {...}, {...}, ... ], "pages" : 5 // 總頁數 } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/759b6430ed5b