搜尋
首頁Javajava教程SpringBoot MP簡單的分頁查詢測試怎麼實現

導入最新的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) {}
}

我們可以發現它有一個私有的屬性清單 List 而這個鍊錶中的元素型別是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) {
    }
}

不難發現這個介面的內容大致就是設定預設的屬性,從程式碼的意思上就是提供預設的資料庫操作執行期間前後執行的一些邏輯,誰實現它的方法會得到新的功能?

再看看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 {...........省略之后全部的内容........}

我們可以輕易地發現這個方法實作了InnerInterceptor介面中的方法,所以我們需要好好檢視它的原始碼來理清邏輯。

我們知道了分頁外掛和核心外掛的關係,也就是我們可以將分頁外掛程式加入到核心外掛內部的外掛鍊錶中去,從而實現多功能外掛的使用。

設定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() {
        /*创建mp拦截器*/
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        /*创建分页插件*/
        PaginationInnerInterceptor pagInterceptor = new PaginationInnerInterceptor();
        /*设置请求的页面大于最大页容量后的请求操作,true回调第一页,false继续翻页,默认翻页*/
        pagInterceptor.setOverflow(false);
        /*设置单页分页的条数限制*/
        pagInterceptor.setMaxLimit(500L);
        /*设置数据库类型*/
        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> {
}

為介面建立一個服務類別(一定按照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;
    /**
     * 根据传入的页码进行翻页
     *
     * @param current 当前页码(已经约定每页数据量是1条)
     * @return 分页对象
     */
    public Page<Product> page(Long current) {
        /*current首页位置,写1就是第一页,没有0页之说,size每页显示的数据量*/
        Page<Product> productPage = new Page<>(current, 1);
        /*条件查询分页*/
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        productMapper.selectPage(productPage, queryWrapper);
        return productPage;
    }
}

到這裡我們可以看到分頁的具體方法就是,先創建一個分頁對象,規定頁碼和每一頁的資料量的大小,其次確定查詢操作的範圍,並使用BaseMapper給予我們的查詢分頁方法selectPage(E page,Wapper 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("每页显示数量"+productIPage.getSize());
        System.out.println("总页数"+productIPage.getPages());
        System.out.println("数据总量"+productIPage.getTotal());
    }

執行檢視分頁結果:

SpringBoot MP簡單的分頁查詢測試怎麼實現

#我們可以發現都正常的依照我們傳入的頁碼去查詢對應的頁數據了,因為我設定的每頁只顯示一條數據,所以ID如果對應頁碼就表示分頁成功。

以上是SpringBoot MP簡單的分頁查詢測試怎麼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
為什麼Java是開發跨平台桌面應用程序的流行選擇?為什麼Java是開發跨平台桌面應用程序的流行選擇?Apr 25, 2025 am 12:23 AM

javaispopularforcross-platformdesktopapplicationsduetoits“ writeonce,runany where”哲學。 1)itusesbytiesebyTecodeThatrunsonAnyJvm-備用Platform.2)librarieslikeslikeslikeswingingandjavafxhelpcreatenative-lookingenative-lookinguisis.3)

討論可能需要在Java中編寫平台特定代碼的情況。討論可能需要在Java中編寫平台特定代碼的情況。Apr 25, 2025 am 12:22 AM

在Java中編寫平台特定代碼的原因包括訪問特定操作系統功能、與特定硬件交互和優化性能。 1)使用JNA或JNI訪問Windows註冊表;2)通過JNI與Linux特定硬件驅動程序交互;3)通過JNI使用Metal優化macOS上的遊戲性能。儘管如此,編寫平台特定代碼會影響代碼的可移植性、增加複雜性、可能帶來性能開銷和安全風險。

與平台獨立性相關的Java開發的未來趨勢是什麼?與平台獨立性相關的Java開發的未來趨勢是什麼?Apr 25, 2025 am 12:12 AM

Java將通過雲原生應用、多平台部署和跨語言互操作進一步提昇平台獨立性。 1)雲原生應用將使用GraalVM和Quarkus提升啟動速度。 2)Java將擴展到嵌入式設備、移動設備和量子計算機。 3)通過GraalVM,Java將與Python、JavaScript等語言無縫集成,增強跨語言互操作性。

Java的強鍵入如何有助於平台獨立性?Java的強鍵入如何有助於平台獨立性?Apr 25, 2025 am 12:11 AM

Java的強類型系統通過類型安全、統一的類型轉換和多態性確保了平台獨立性。 1)類型安全在編譯時進行類型檢查,避免運行時錯誤;2)統一的類型轉換規則在所有平台上一致;3)多態性和接口機制使代碼在不同平台上行為一致。

說明Java本機界面(JNI)如何損害平台獨立性。說明Java本機界面(JNI)如何損害平台獨立性。Apr 25, 2025 am 12:07 AM

JNI會破壞Java的平台獨立性。 1)JNI需要特定平台的本地庫,2)本地代碼需在目標平台編譯和鏈接,3)不同版本的操作系統或JVM可能需要不同的本地庫版本,4)本地代碼可能引入安全漏洞或導致程序崩潰。

是否有任何威脅或增強Java平台獨立性的新興技術?是否有任何威脅或增強Java平台獨立性的新興技術?Apr 24, 2025 am 12:11 AM

新興技術對Java的平台獨立性既有威脅也有增強。 1)雲計算和容器化技術如Docker增強了Java的平台獨立性,但需要優化以適應不同雲環境。 2)WebAssembly通過GraalVM編譯Java代碼,擴展了其平台獨立性,但需與其他語言競爭性能。

JVM的實現是什麼,它們都提供了相同的平台獨立性?JVM的實現是什麼,它們都提供了相同的平台獨立性?Apr 24, 2025 am 12:10 AM

不同JVM實現都能提供平台獨立性,但表現略有不同。 1.OracleHotSpot和OpenJDKJVM在平台獨立性上表現相似,但OpenJDK可能需額外配置。 2.IBMJ9JVM在特定操作系統上表現優化。 3.GraalVM支持多語言,需額外配置。 4.AzulZingJVM需特定平台調整。

平台獨立性如何降低發展成本和時間?平台獨立性如何降低發展成本和時間?Apr 24, 2025 am 12:08 AM

平台獨立性通過在多種操作系統上運行同一套代碼,降低開發成本和縮短開發時間。具體表現為:1.減少開發時間,只需維護一套代碼;2.降低維護成本,統一測試流程;3.快速迭代和團隊協作,簡化部署過程。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。