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

SpringBoot?MP簡單的分頁查詢測試實現(xiàn)步驟分解

 更新時間:2023年04月03日 10:56:57   作者:ForestSpringH  
好久沒水后端的東西了,最近在做vue項目寫前端的代碼,所以cloud也停進度了,吃完飯突然記得我沒有在博客里寫分頁的東西,雖然項目中用到了,但是沒有拎出來,這里就拎出來看看

導入最新的mp依賴是第一步不然太低的版本什么都做不了,3,1以下的好像連分頁插件都沒有加進去,所以我們用最新的3.5的,保證啥都有:

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>

這里我們需要認識兩個插件:mp的核心插件MybatisPlusInterceptor與自動分頁插件PaginationInnerInterceptor。

MybatisPlusInterceptor的源碼(去掉中間的處理代碼):

public class MybatisPlusInterceptor implements Interceptor {
    private List<InnerInterceptor> interceptors = new ArrayList();
    public MybatisPlusInterceptor() {}
    public Object intercept(Invocation invocation) throws Throwable {}
    public Object plugin(Object target) {}
    public void addInnerInterceptor(InnerInterceptor innerInterceptor) {}
    public List<InnerInterceptor> getInterceptors() {}
    public void setProperties(Properties properties) {}
    public void setInterceptors(final List<InnerInterceptor> interceptors) {}
}

我們可以發(fā)現(xiàn)它有一個私有的屬性列表 List<InnerInterceptor> 而這個鏈表中的元素類型是InnerInterceptor。

InnerInterceptor源碼:

public interface InnerInterceptor {
    default boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        return true;
    }
    default void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    }
    default boolean willDoUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        return true;
    }
    default void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
    }
    default void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
    }
    default void beforeGetBoundSql(StatementHandler sh) {
    }
    default void setProperties(Properties properties) {
    }
}

不難發(fā)現(xiàn)這個接口的內容大致就是設置默認的屬性,從代碼的意思上就是提供默認的數(shù)據(jù)庫操作執(zhí)行時期前后執(zhí)行的一些邏輯,誰實現(xiàn)它的方法會得到新的功能?

再看看PaginationInnerInterceptor插件的源碼:

public class PaginationInnerInterceptor implements InnerInterceptor {
    protected static final List<SelectItem> COUNT_SELECT_ITEM = Collections.singletonList((new SelectExpressionItem((new Column()).withColumnName("COUNT(*)"))).withAlias(new Alias("total")));
    protected static final Map<String, MappedStatement> countMsCache = new ConcurrentHashMap();
    protected final Log logger = LogFactory.getLog(this.getClass());
    protected boolean overflow;
    protected Long maxLimit;
    private DbType dbType;
    private IDialect dialect;
    protected boolean optimizeJoin = true;
    public PaginationInnerInterceptor(DbType dbType) {
        this.dbType = dbType;
    }
    public PaginationInnerInterceptor(IDialect dialect) {
        this.dialect = dialect;
    }
    public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        IPage<?> page = (IPage)ParameterUtils.findPage(parameter).orElse((Object)null);
        if (page != null && page.getSize() >= 0L && page.searchCount()) {
            MappedStatement countMs = this.buildCountMappedStatement(ms, page.countId());
            BoundSql countSql;
            if (countMs != null) {
                countSql = countMs.getBoundSql(parameter);
            } else {
                countMs = this.buildAutoCountMappedStatement(ms);
                String countSqlStr = this.autoCountSql(page, boundSql.getSql());
                MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
                countSql = new BoundSql(countMs.getConfiguration(), countSqlStr, mpBoundSql.parameterMappings(), parameter);
                PluginUtils.setAdditionalParameter(countSql, mpBoundSql.additionalParameters());
            }
            CacheKey cacheKey = executor.createCacheKey(countMs, parameter, rowBounds, countSql);
            List<Object> result = executor.query(countMs, parameter, rowBounds, resultHandler, cacheKey, countSql);
            long total = 0L;
            if (CollectionUtils.isNotEmpty(result)) {
                Object o = result.get(0);
                if (o != null) {
                    total = Long.parseLong(o.toString());
                }
            }
            page.setTotal(total);
            return this.continuePage(page);
        } else {
            return true;
        }
    }
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {...........省略之后全部的內容........}

我們不難發(fā)現(xiàn)它實現(xiàn)了來自于InnerInterceptor的方法,這里面的源碼有時間需要好好處處邏輯。

我們知道了分頁插件和核心插件的關系,也就是我們可以將分頁插件添加入核心插件內部的插件鏈表中去,從而實現(xiàn)多功能插件的使用。

配置mp插件,并將插件交由spring管理(我們用的是springboot進行測試所以不需要使用xml文件):

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MpConfig {
    /*分頁插件的配置*/
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        /*創(chuàng)建mp攔截器*/
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        /*創(chuàng)建分頁插件*/
        PaginationInnerInterceptor pagInterceptor = new PaginationInnerInterceptor();
        /*設置請求的頁面大于最大頁容量后的請求操作,true回調第一頁,false繼續(xù)翻頁,默認翻頁*/
        pagInterceptor.setOverflow(false);
        /*設置單頁分頁的條數(shù)限制*/
        pagInterceptor.setMaxLimit(500L);
        /*設置數(shù)據(jù)庫類型*/
        pagInterceptor.setDbType(DbType.MYSQL);
        /*將分頁攔截器添加到mp攔截器中*/
        interceptor.addInnerInterceptor(pagInterceptor);
        return interceptor;
    }
}

配置完之后寫一個Mapper接口:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hlc.mp.entity.Product;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ProductMapper extends BaseMapper<Product> {
}

為接口創(chuàng)建一個服務類(一定按照mp編碼的風格來):

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlc.mp.entity.Product;
import com.hlc.mp.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service(value = "ProductService")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
        implements IService<Product> {
    @Autowired
    ProductMapper productMapper;
    /**
     * 根據(jù)傳入的頁碼進行翻頁
     *
     * @param current 當前頁碼(已經(jīng)約定每頁數(shù)據(jù)量是1條)
     * @return 分頁對象
     */
    public Page<Product> page(Long current) {
        /*current首頁位置,寫1就是第一頁,沒有0頁之說,size每頁顯示的數(shù)據(jù)量*/
        Page<Product> productPage = new Page<>(current, 1);
        /*條件查詢分頁*/
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        productMapper.selectPage(productPage, queryWrapper);
        return productPage;
    }
}

到這里我們可以看到分頁的具體方法就是,先創(chuàng)建一個分頁對象,規(guī)定頁碼和每一頁的數(shù)據(jù)量的大小,其次確定查詢操作的范圍,并使用BaseMapper<T>給予我們的查詢分頁方法selectPage(E page,Wapper<T> queryWapper)進行查詢分頁的操作。

測試類:

    @Test
    public void testPage(){
        IPage<Product> productIPage = productService.page(2L);
        productIPage.getRecords().forEach(System.out::println);
        System.out.println("當前頁碼"+productIPage.getCurrent());
        System.out.println("每頁顯示數(shù)量"+productIPage.getSize());
        System.out.println("總頁數(shù)"+productIPage.getPages());
        System.out.println("數(shù)據(jù)總量"+productIPage.getTotal());
    }

運行查看分頁結果:

我們可以發(fā)現(xiàn)都正常的按照我們傳入的頁碼去查詢對應的頁數(shù)據(jù)了,因為我設置的每頁只展示一條數(shù)據(jù),所以ID如果對應頁碼就說明分頁成功。

到此這篇關于SpringBoot MP簡單的分頁查詢測試實現(xiàn)步驟分解的文章就介紹到這了,更多相關SpringBoot MP分頁查詢測試內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Maven優(yōu)雅的添加第三方Jar包的方法

    Maven優(yōu)雅的添加第三方Jar包的方法

    下面小編就為大家?guī)硪黄狹aven優(yōu)雅的添加第三方Jar包的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • Spring boot定時任務的原理及動態(tài)創(chuàng)建詳解

    Spring boot定時任務的原理及動態(tài)創(chuàng)建詳解

    這篇文章主要給大家介紹了關于Spring boot定時任務的原理及動態(tài)創(chuàng)建的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-03-03
  • Java實現(xiàn)Excel文件加密解密的示例代碼

    Java實現(xiàn)Excel文件加密解密的示例代碼

    設置excel文件保護時,通??蛇x擇對整個工作簿進行加密保護。無需設置文檔保護時,可撤銷密碼保護,即解密文檔。本文將通過java程序演示以上加密、解密方法的實現(xiàn),感興趣的可以了解一下
    2022-05-05
  • java實現(xiàn)電腦端掃描二維碼

    java實現(xiàn)電腦端掃描二維碼

    這篇文章主要為大家詳細介紹了java實現(xiàn)電腦端掃描二維碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-10-10
  • Spring Boot mybatis-config 和 log4j 輸出sql 日志的方式

    Spring Boot mybatis-config 和 log4j 輸出sql 日志的方式

    這篇文章主要介紹了Spring Boot mybatis-config 和 log4j 輸出sql 日志的方式,本文通過實例圖文相結合給大家介紹的非常詳細,需要的朋友可以參考下
    2021-07-07
  • 為什么SpringMVC中請求的body不支持多次讀取

    為什么SpringMVC中請求的body不支持多次讀取

    這篇文章主要介紹了為什么SpringMVC中請求的body不支持多次讀取,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • Java 異步回調機制實例分析

    Java 異步回調機制實例分析

    這篇文章主要介紹了Java 異步回調機制實例解析的相關資料,需要的朋友可以參考下
    2017-02-02
  • java 實例化類詳解及簡單實例

    java 實例化類詳解及簡單實例

    這篇文章主要介紹了java 實例化類詳解及簡單實例的相關資料,需要的朋友可以參考下
    2017-03-03
  • 200行java代碼實現(xiàn)2048小游戲

    200行java代碼實現(xiàn)2048小游戲

    這篇文章主要為大家詳細介紹了200行java代碼實現(xiàn)2048小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • java計算時間差的方法

    java計算時間差的方法

    這篇文章主要介紹了java計算時間差的方法,涉及java針對時間的轉換與計算相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-07-07

最新評論