mybatis-plus分頁(yè)查詢(xún)的實(shí)現(xiàn)實(shí)例
一、官方文檔
Mybatis-Plus分頁(yè)插件:https://baomidou.com/pages/97710a/
PageHelper分頁(yè)插件:https://pagehelper.github.io/
Tip??:官網(wǎng)鏈接,第一手資料。
二、內(nèi)置的分頁(yè)方法
1、內(nèi)置方法
在Mybatis-Plus的BaseMapper中,已經(jīng)內(nèi)置了2個(gè)支持分頁(yè)的方法:
public interface BaseMapper<T> extends Mapper<T> {
<P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);
<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);
……
}
2、selectPage單元測(cè)試
使用selectPage方法分頁(yè)查詢(xún)年紀(jì)age = 13的用戶(hù)。
@Test
public void testPage() {
System.out.println("----- selectPage method test ------");
//分頁(yè)參數(shù)
Page<User> page = Page.of(1,10);
//queryWrapper組裝查詢(xún)where條件
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getAge,13);
userMapper.selectPage(page,queryWrapper);
page.getRecords().forEach(System.out::println);
}
執(zhí)行結(jié)果:

查詢(xún)出了表中滿(mǎn)足條件的所有記錄,說(shuō)明默認(rèn)情況下,selectPage方法并不能實(shí)現(xiàn)分頁(yè)查詢(xún)。
3、PaginationInnerInterceptor分頁(yè)插件配置
mybatis-plus中的分頁(yè)查詢(xún)功能,需要PaginationInnerInterceptor分頁(yè)插件的支持,否則分頁(yè)查詢(xún)功能不能生效。
@Configuration
public class MybatisPlusConfig {
/**
* 新增分頁(yè)攔截器,并設(shè)置數(shù)據(jù)庫(kù)類(lèi)型為mysql
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
再次執(zhí)行單元測(cè)試:

先執(zhí)行count查詢(xún)查詢(xún)滿(mǎn)足條件的記錄總數(shù),然后執(zhí)行l(wèi)imit分頁(yè)查詢(xún),查詢(xún)分頁(yè)記錄,說(shuō)明分頁(yè)查詢(xún)生效。
三、分頁(yè)原理分析
查看PaginationInnerInterceptor攔截器中的核心實(shí)現(xiàn):
//select查詢(xún)請(qǐng)求的前置方法
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
//根據(jù)請(qǐng)求參數(shù)來(lái)判斷是否采用分頁(yè)查詢(xún),參數(shù)中含有IPage類(lèi)型的參數(shù),則執(zhí)行分頁(yè)
IPage<?> page = (IPage)ParameterUtils.findPage(parameter).orElse((Object)null);
if (null != page) {
boolean addOrdered = false;
String buildSql = boundSql.getSql();
List<OrderItem> orders = page.orders();
if (CollectionUtils.isNotEmpty(orders)) {
addOrdered = true;
buildSql = this.concatOrderBy(buildSql, orders);
}
//根據(jù)page參數(shù),組裝分頁(yè)查詢(xún)sql
Long _limit = page.maxLimit() != null ? page.maxLimit() : this.maxLimit;
if (page.getSize() < 0L && null == _limit) {
if (addOrdered) {
PluginUtils.mpBoundSql(boundSql).sql(buildSql);
}
} else {
this.handlerLimit(page, _limit);
IDialect dialect = this.findIDialect(executor);
Configuration configuration = ms.getConfiguration();
DialectModel model = dialect.buildPaginationSql(buildSql, page.offset(), page.getSize());
MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
List<ParameterMapping> mappings = mpBoundSql.parameterMappings();
Map<String, Object> additionalParameter = mpBoundSql.additionalParameters();
model.consumers(mappings, configuration, additionalParameter);
mpBoundSql.sql(model.getDialectSql());
mpBoundSql.parameterMappings(mappings);
}
}
}
再來(lái)看看ParameterUtils.findPage()方法的實(shí)現(xiàn):
//發(fā)現(xiàn)參數(shù)中的IPage對(duì)象
public static Optional<IPage> findPage(Object parameterObject) {
if (parameterObject != null) {
//如果是多個(gè)參數(shù),會(huì)轉(zhuǎn)為map對(duì)象;只要任意一個(gè)value中包含IPage類(lèi)型的對(duì)象,返回IPage對(duì)象
if (parameterObject instanceof Map) {
Map<?, ?> parameterMap = (Map)parameterObject;
Iterator var2 = parameterMap.entrySet().iterator();
while(var2.hasNext()) {
Entry entry = (Entry)var2.next();
if (entry.getValue() != null && entry.getValue() instanceof IPage) {
return Optional.of((IPage)entry.getValue());
}
}
//如果只有單個(gè)參數(shù),且類(lèi)型為IPage,則返回IPage對(duì)象
} else if (parameterObject instanceof IPage) {
return Optional.of((IPage)parameterObject);
}
}
return Optional.empty();
}
小結(jié):mybatis-plus分頁(yè)查詢(xún)的實(shí)現(xiàn)原理:
1、由分頁(yè)攔截器PaginationInnerInterceptor攔截所有查詢(xún)請(qǐng)求,在執(zhí)行查詢(xún)前判斷參數(shù)中是否包含IPage類(lèi)型的參數(shù)。
2、如果包含IPage類(lèi)型的參數(shù),則根據(jù)分頁(yè)信息,重新組裝成分頁(yè)查詢(xún)的SQL。
四、自定義分頁(yè)方法
搞清楚mybatis-plus中分頁(yè)查詢(xún)的原理,我們來(lái)自定義分頁(yè)查詢(xún)方法。
這里我使用的是mybatis-plus 3.5.2的版本。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
在UserMapper中新增selectPageByDto方法。
public interface UserMapper extends CommonMapper<User> {
/**
* 不分頁(yè)dto條件查詢(xún)
* @param userDto
* @return
*/
List<User> selectByDto(@Param("userDto") UserDto userDto);
/**
* 支持分頁(yè)的dto條件查詢(xún)
* @param page
* @param userDto
* @return
*/
IPage<User> selectPageByDto(IPage<User> page,@Param("userDto") UserDto userDto);
}
說(shuō)明:
1、mybatis-plus中分頁(yè)接口需要包含一個(gè)IPage類(lèi)型的參數(shù)。
2、多個(gè)實(shí)體參數(shù),需要添加@Param參數(shù)注解,方便在xml中配置sql時(shí)獲取參數(shù)值。
UserMapper.xml中的分頁(yè)sql配置:這里由于selectByDto和selectPageByDto兩個(gè)方法都是根據(jù)dto進(jìn)行查詢(xún),
sql語(yǔ)句完全一樣,所以將相同的sql抽取了出來(lái),然后用include標(biāo)簽去引用。
<sql id="selectByDtoSql">
select * from user t
<where>
<if test="userDto.name != null and userDto.name != '' ">
AND t.name like CONCAT('%',#{userDto.name},'%')
</if>
<if test="userDto.age != null">
AND t.age = #{userDto.age}
</if>
</where>
</sql>
<select id="selectByDto" resultType="com.laowan.mybatis_plus.model.User">
<include refid="selectByDtoSql"/>
</select>
<select id="selectPageByDto" resultType="com.laowan.mybatis_plus.model.User">
<include refid="selectByDtoSql"/>
</select>
1、2種分頁(yè)寫(xiě)法
方式一:Page對(duì)象既作為參數(shù),也作為查詢(xún)結(jié)果接受體
@Test
public void testSelectPageByDto() {
System.out.println("----- SelectPageByDto method test ------");
//分頁(yè)參數(shù)Page,也作為查詢(xún)結(jié)果接受體
Page<User> page = Page.of(1,10);
//查詢(xún)參數(shù)
UserDto userDto = new UserDto();
userDto.setName("test");
userMapper.selectPageByDto(page,userDto);
page.getRecords().forEach(System.out::println);
}
- 方式二:Page作為參數(shù),用一個(gè)新的IPage對(duì)象接受查詢(xún)結(jié)果。
@Test
public void testSelectPageByDto() {
System.out.println("----- SelectPageByDto method test ------");
//查詢(xún)參數(shù)
UserDto userDto = new UserDto();
userDto.setName("test");
//PageDTO.of(1,10)對(duì)象只作為查詢(xún)參數(shù),
IPage<User> page = userMapper.selectPageByDto(PageDTO.of(1,10),userDto);
page.getRecords().forEach(System.out::println);
}
下面是官網(wǎng)的一些說(shuō)明:

這是官網(wǎng)針對(duì)自定義分頁(yè)的說(shuō)明。
個(gè)人建議:如果定義的方法名中包含Page,說(shuō)明該方法是用來(lái)進(jìn)行分頁(yè)查詢(xún)的,返回結(jié)果盡量用IPage,而不要用List。防止出現(xiàn)不必要的錯(cuò)誤,也更符合見(jiàn)名知意和單一指責(zé)原則。
2、利用page.convert方法實(shí)現(xiàn)Do到Vo的轉(zhuǎn)換
public IPage<UserVO> list(PageRequest request) {
IPage<UserDO> page = new Page(request.getPageNum(), request.pageSize());
LambdaQueryWrapper<UserDO> qw = Wrappers.lambdaQuery();
page = userMapper.selectPage(page, qw);
return page.convert(u->{
UserVO v = new UserVO();
BeanUtils.copyProperties(u, v);
return v;
});
}
五、分頁(yè)插件 PageHelper
很多人已經(jīng)習(xí)慣了在mybatis框架下使用PageHelper進(jìn)行分頁(yè)查詢(xún),在mybatis-plus框架下依然也可以使用,和mybatis-plus框架自帶的分頁(yè)插件沒(méi)有明顯的高下之分。
個(gè)人認(rèn)為mybatis-plus的分頁(yè)實(shí)現(xiàn)可以從方法命名、方法傳參方面更好的規(guī)整代碼。而PageHelper的實(shí)現(xiàn)對(duì)代碼的侵入性更強(qiáng),不符合單一指責(zé)原則。
推薦在同一個(gè)項(xiàng)目中,只選用一種分頁(yè)方式,統(tǒng)一代碼風(fēng)格。
PageHelper的使用:
1.引入maven依賴(lài)
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>最新版本</version>
</dependency>
2.PageHelper分頁(yè)查詢(xún)
代碼如下(示例):
//獲取第1頁(yè),10條內(nèi)容,默認(rèn)查詢(xún)總數(shù)count PageHelper.startPage(1, 10); List<Country> list = countryMapper.selectAll(); //用PageInfo對(duì)結(jié)果進(jìn)行包裝 PageInfo page = new PageInfo(list);
總結(jié)
本文主要對(duì)mybatis-plus分頁(yè)查詢(xún)的原理和使用進(jìn)行了詳細(xì)介紹。
1、要開(kāi)啟mybatis-plus分頁(yè)查詢(xún)功能首先需要配置PaginationInnerInterceptor分頁(yè)查詢(xún)插件。
2、PaginationInnerInterceptor分頁(yè)查詢(xún)插件的實(shí)現(xiàn)原理是:攔截所有查詢(xún)請(qǐng)求,分析查詢(xún)參數(shù)中是否包含IPage類(lèi)型的參數(shù)。如果有則根據(jù)分頁(yè)信息和數(shù)據(jù)庫(kù)類(lèi)型重組sql。
3、提供了2種分頁(yè)查詢(xún)的寫(xiě)法。
4、和經(jīng)典的PageHelper分頁(yè)插件進(jìn)行了對(duì)比。兩者的使用都非常簡(jiǎn)單,在單一項(xiàng)目中任選一種,統(tǒng)一代碼風(fēng)格即可。
到此這篇關(guān)于mybatis-plus分頁(yè)查詢(xún)的實(shí)現(xiàn)實(shí)例的文章就介紹到這了,更多相關(guān)mybatis-plus分頁(yè)查詢(xún)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot使用mybatis-plus分頁(yè)查詢(xún)無(wú)效的問(wèn)題解決
- SpringBoot整合mybatis-plus實(shí)現(xiàn)分頁(yè)查詢(xún)功能
- mybatis-plus多表分頁(yè)查詢(xún)最佳實(shí)現(xiàn)方法(非常簡(jiǎn)單)
- mybatis-plus分頁(yè)查詢(xún)?nèi)N方法小結(jié)
- Mybatis-plus分頁(yè)查詢(xún)不生效問(wèn)題排查全過(guò)程
- 如何使用mybatis-plus實(shí)現(xiàn)分頁(yè)查詢(xún)功能
- 一文搞懂Mybatis-plus的分頁(yè)查詢(xún)操作
- MyBatis-Plus?分頁(yè)查詢(xún)的實(shí)現(xiàn)示例
- springboot整合mybatis-plus 實(shí)現(xiàn)分頁(yè)查詢(xún)功能
- mybatis-plus分頁(yè)查詢(xún)的實(shí)現(xiàn)示例
- mybatis-plus 實(shí)現(xiàn)分頁(yè)查詢(xún)的示例代碼
相關(guān)文章
SpringBoot如何讀取application.properties配置文件
這篇文章主要介紹了SpringBoot如何讀取application.properties配置文件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
詳解context root修改無(wú)效web修改項(xiàng)目路徑(eclipse)
這篇文章主要介紹了詳解context root修改無(wú)效web修改項(xiàng)目路徑(eclipse)的相關(guān)資料,需要的朋友可以參考下2017-04-04
Java中forEach使用lambda表達(dá)式,數(shù)組和集合的區(qū)別說(shuō)明
這篇文章主要介紹了Java中forEach使用lambda表達(dá)式,數(shù)組和集合的區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
java虛擬機(jī)學(xué)習(xí)筆記基礎(chǔ)篇
在本篇文章里小編給大家整理的是關(guān)于java虛擬機(jī)學(xué)習(xí)筆記的相關(guān)內(nèi)容,分享了一些基礎(chǔ)知識(shí)點(diǎn),需要的朋友們參考下。2019-06-06
解決在IDEA中創(chuàng)建多級(jí)package的問(wèn)題
這篇文章主要介紹了解決在IDEA中創(chuàng)建多級(jí)package的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
Java防止頻繁請(qǐng)求、重復(fù)提交的操作代碼(后端防抖操作)
在客戶(hù)端網(wǎng)絡(luò)慢或者服務(wù)器響應(yīng)慢時(shí),用戶(hù)有時(shí)是會(huì)頻繁刷新頁(yè)面或重復(fù)提交表單的,這樣是會(huì)給服務(wù)器造成不小的負(fù)擔(dān)的,同時(shí)在添加數(shù)據(jù)時(shí)有可能造成不必要的麻煩,今天通過(guò)本文給大家介紹下Java防止頻繁請(qǐng)求、重復(fù)提交的操作代碼,一起看看吧2022-04-04
java開(kāi)發(fā)線(xiàn)上事故理解RocketMQ異步精髓
這篇文章主要介紹了java開(kāi)發(fā)線(xiàn)上事故理解RocketMQ異步精髓2022-07-07
JAVA后臺(tái)轉(zhuǎn)換成樹(shù)結(jié)構(gòu)數(shù)據(jù)返回給前端的實(shí)現(xiàn)方法
這篇文章主要介紹了JAVA后臺(tái)轉(zhuǎn)換成樹(shù)結(jié)構(gòu)數(shù)據(jù)返回給前端的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03

