欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mybatis-plus分頁查詢的實現(xiàn)實例

 更新時間:2024年06月23日 14:56:24   作者:斗者_2013  
頁查詢是一項常用的數(shù)據(jù)庫查詢方法,本文主要介紹了mybatis-plus分頁查詢的實現(xiàn)實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、官方文檔

Mybatis-Plus分頁插件:https://baomidou.com/pages/97710a/

PageHelper分頁插件:https://pagehelper.github.io/

Tip??:官網(wǎng)鏈接,第一手資料。

二、內(nèi)置的分頁方法

1、內(nèi)置方法

Mybatis-PlusBaseMapper中,已經(jīng)內(nèi)置了2個支持分頁的方法:

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單元測試

使用selectPage方法分頁查詢年紀age = 13的用戶。

    @Test
    public void testPage() {
        System.out.println("----- selectPage method test ------");
        //分頁參數(shù)
        Page<User> page = Page.of(1,10);

        //queryWrapper組裝查詢where條件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAge,13);
        userMapper.selectPage(page,queryWrapper);
        page.getRecords().forEach(System.out::println);
    }

執(zhí)行結(jié)果:

在這里插入圖片描述

查詢出了表中滿足條件的所有記錄,說明默認情況下,selectPage方法并不能實現(xiàn)分頁查詢。

3、PaginationInnerInterceptor分頁插件配置

mybatis-plus中的分頁查詢功能,需要PaginationInnerInterceptor分頁插件的支持,否則分頁查詢功能不能生效。

@Configuration
public class MybatisPlusConfig {
    /**
     * 新增分頁攔截器,并設(shè)置數(shù)據(jù)庫類型為mysql
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

再次執(zhí)行單元測試:

在這里插入圖片描述

先執(zhí)行count查詢查詢滿足條件的記錄總數(shù),然后執(zhí)行l(wèi)imit分頁查詢,查詢分頁記錄,說明分頁查詢生效。

三、分頁原理分析

查看PaginationInnerInterceptor攔截器中的核心實現(xiàn):

//select查詢請求的前置方法
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    //根據(jù)請求參數(shù)來判斷是否采用分頁查詢,參數(shù)中含有IPage類型的參數(shù),則執(zhí)行分頁
    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ù),組裝分頁查詢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);
        }
    }
}

再來看看ParameterUtils.findPage()方法的實現(xiàn):

//發(fā)現(xiàn)參數(shù)中的IPage對象
public static Optional<IPage> findPage(Object parameterObject) {
    if (parameterObject != null) {
        //如果是多個參數(shù),會轉(zhuǎn)為map對象;只要任意一個value中包含IPage類型的對象,返回IPage對象
        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());
                }
            }
            
         //如果只有單個參數(shù),且類型為IPage,則返回IPage對象
        } else if (parameterObject instanceof IPage) {
            return Optional.of((IPage)parameterObject);
        }
    }

    return Optional.empty();
}

小結(jié):mybatis-plus分頁查詢的實現(xiàn)原理:
1、由分頁攔截器PaginationInnerInterceptor攔截所有查詢請求,在執(zhí)行查詢前判斷參數(shù)中是否包含IPage類型的參數(shù)。
2、如果包含IPage類型的參數(shù),則根據(jù)分頁信息,重新組裝成分頁查詢的SQL。

四、自定義分頁方法

搞清楚mybatis-plus中分頁查詢的原理,我們來自定義分頁查詢方法。

這里我使用的是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> {

    /**
     * 不分頁dto條件查詢
     * @param userDto
     * @return
     */
    List<User> selectByDto(@Param("userDto") UserDto userDto);


    /**
     * 支持分頁的dto條件查詢
     * @param page
     * @param userDto
     * @return
     */
    IPage<User> selectPageByDto(IPage<User> page,@Param("userDto") UserDto userDto);
}

說明:
1、mybatis-plus中分頁接口需要包含一個IPage類型的參數(shù)。
2、多個實體參數(shù),需要添加@Param參數(shù)注解,方便在xml中配置sql時獲取參數(shù)值。

UserMapper.xml中的分頁sql配置:這里由于selectByDto和selectPageByDto兩個方法都是根據(jù)dto進行查詢,
sql語句完全一樣,所以將相同的sql抽取了出來,然后用include標簽去引用。

 <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種分頁寫法

方式一:Page對象既作為參數(shù),也作為查詢結(jié)果接受體

@Test
  public void testSelectPageByDto() {
       System.out.println("----- SelectPageByDto method test ------");
       //分頁參數(shù)Page,也作為查詢結(jié)果接受體
       Page<User> page = Page.of(1,10);
       //查詢參數(shù)
       UserDto userDto = new UserDto();
       userDto.setName("test");
       
       userMapper.selectPageByDto(page,userDto);

       page.getRecords().forEach(System.out::println);
   }
  • 方式二:Page作為參數(shù),用一個新的IPage對象接受查詢結(jié)果。
    @Test
    public void testSelectPageByDto() {
        System.out.println("----- SelectPageByDto method test ------");
        //查詢參數(shù)
        UserDto userDto = new UserDto();
        userDto.setName("test");

        //PageDTO.of(1,10)對象只作為查詢參數(shù),
        IPage&lt;User&gt; page = userMapper.selectPageByDto(PageDTO.of(1,10),userDto);
        
        page.getRecords().forEach(System.out::println);
    }

下面是官網(wǎng)的一些說明:

在這里插入圖片描述

這是官網(wǎng)針對自定義分頁的說明。

個人建議:如果定義的方法名中包含Page,說明該方法是用來進行分頁查詢的,返回結(jié)果盡量用IPage,而不要用List。防止出現(xiàn)不必要的錯誤,也更符合見名知意和單一指責(zé)原則。

2、利用page.convert方法實現(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;
  });
}

五、分頁插件 PageHelper

很多人已經(jīng)習(xí)慣了在mybatis框架下使用PageHelper進行分頁查詢,在mybatis-plus框架下依然也可以使用,和mybatis-plus框架自帶的分頁插件沒有明顯的高下之分。

個人認為mybatis-plus的分頁實現(xiàn)可以從方法命名、方法傳參方面更好的規(guī)整代碼。而PageHelper的實現(xiàn)對代碼的侵入性更強,不符合單一指責(zé)原則。

推薦在同一個項目中,只選用一種分頁方式,統(tǒng)一代碼風(fēng)格

PageHelper的使用:

1.引入maven依賴

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>最新版本</version>
</dependency>

2.PageHelper分頁查詢

代碼如下(示例):

//獲取第1頁,10條內(nèi)容,默認查詢總數(shù)count
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectAll();
//用PageInfo對結(jié)果進行包裝
PageInfo page = new PageInfo(list);

總結(jié)

本文主要對mybatis-plus分頁查詢的原理和使用進行了詳細介紹。

1、要開啟mybatis-plus分頁查詢功能首先需要配置PaginationInnerInterceptor分頁查詢插件。

2、PaginationInnerInterceptor分頁查詢插件的實現(xiàn)原理是:攔截所有查詢請求,分析查詢參數(shù)中是否包含IPage類型的參數(shù)。如果有則根據(jù)分頁信息和數(shù)據(jù)庫類型重組sql。

3、提供了2種分頁查詢的寫法。

4、和經(jīng)典的PageHelper分頁插件進行了對比。兩者的使用都非常簡單,在單一項目中任選一種,統(tǒng)一代碼風(fēng)格即可。

到此這篇關(guān)于mybatis-plus分頁查詢的實現(xiàn)實例的文章就介紹到這了,更多相關(guān)mybatis-plus分頁查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論