上一節(jié),簡(jiǎn)單講述了 mybatis-plus 搭建與使用入門,這一節(jié),簡(jiǎn)單講一下如何使用 mp 實(shí)現(xiàn)多表分頁(yè)。
分析
使用的工程,依舊是 spring-boot,關(guān)于分頁(yè),官網(wǎng)給出了一個(gè)單表的demo,其實(shí)多表分頁(yè)實(shí)現(xiàn)原理相同,都是通過(guò) mybatis 的攔截器
(攔截器做了什么?他會(huì)在你的 sql 執(zhí)行之前,為你做一些事情,例如分頁(yè),我們使用了 mp 不用關(guān)心 limit,攔截器為我們拼接。我們也不用關(guān)心總條數(shù),攔截器獲取到我們 sql 后,拼接 select count(*)
為我們查詢總條數(shù),添加到參數(shù)對(duì)象中)。
實(shí)現(xiàn)
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執(zhí)行效率插件【生產(chǎn)環(huán)境可以關(guān)閉】 */ @bean public performanceinterceptor performanceinterceptor() { return new performanceinterceptor(); } /* * 分頁(yè)插件,自動(dòng)識(shí)別數(shù)據(jù)庫(kù)類型 多租戶,請(qǐng)參考官網(wǎng)【插件擴(kuò)展】 */ @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); } |
這里要注意的是,這個(gè) pagination page 是必須要有的,否則 mp 無(wú)法為你實(shí)現(xiàn)分頁(yè)。
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 實(shí)現(xiàn)
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> * 用戶表 服務(wù)實(shí)現(xiàn)類 * </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()); // 當(dāng)前頁(yè),總條數(shù) 構(gòu)造 page 對(duì)象 return page.setrecords( this .basemapper.selectuserlistpage(page, user)); } } |
最后將結(jié)果集 set 到 page 對(duì)象中,page 對(duì)象的 json 結(jié)構(gòu)如下
1
2
3
4
5
6
7
8
9
10
11
12
|
{ "total" : 48 , //總記錄 "size" : 10 , //每頁(yè)顯示多少條 "current" : 1 , //當(dāng)前頁(yè) "records" : [ //結(jié)果集 數(shù)組 {...}, {...}, {...}, ... ], "pages" : 5 // 總頁(yè)數(shù) } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.jianshu.com/p/759b6430ed5b