検索
ホームページJava&#&チュートリアル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 の 2 つのプラグインを知る必要があります。

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;
    }
}

ここでは、ページングの具体的な方法が最初にページングを作成することであることがわかります。オブジェクトで、ページ番号と各ページの 1 ページのデータのサイズを指定し、クエリ操作の範囲を決定し、BaseMapper queryWapper) を使用します。 ;T> クエリ ページング操作を実行します。

テスト クラス:

    @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 の単純なページング クエリ テストを実装する方法

すべてのクエリが次のとおり正常に実行されていることがわかります。渡したページ番号 対応するページ データが存在します。設定した各ページには 1 つのデータのみが表示されるため、ID がページ番号に対応する場合は、ページングが成功したことを意味します。

以上がSpringBoot MP の単純なページング クエリ テストを実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事は亿速云で複製されています。侵害がある場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。