Spring BootとVue.jsのプロジェクトにおけるMyBatis Plus分頁機能

MyBatis Plusの分頁プラグインPageInterceptorCustomは、データベース操作をインターセプトしてページング機能を提供します。以下にその仕組みを説明します。

  1. 分頁プラグインの設定:Spring BootアプリケーションでMybatisPlusConfigクラスを使用し、MybatisPlusInterceptorを設定し、PageInterceptorCustomを追加します。以下がそのコード例です。
@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PageInterceptorCustom(DbType.MYSQL));
        return interceptor;
    }
}

このコードは、MybatisPlusInterceptorインスタンスを作成し、MySQLデータベース用に構成されたPageInterceptorCustomを追加しています。

  1. 分頁機能の使用:分頁クエリを実行する際には、Pageオブジェクトを作成し、それをitemService.page(...)メソッドに渡します。たとえば、以下のようにコントローラー内で使用できます。
@GetMapping("/itemsByPage")
public Result listItemsByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                              @RequestParam(defaultValue = "10") Integer pageSize) {
    Page<Item> page = itemService.page(new Page<>(currentPage, pageSize));
    return Result.success(page);
}

この例では、new Page<>(currentPage, pageSize)により、現在のページ番号と各ページの表示件数を指定したページリクエストが作成されます。

  1. 分頁プラグインの役割PageInterceptorCustomはSQLクエリを自動的に修正し、LIMIT句を追加することでページングを実現します。また、総レコード数も取得し、Pageオブジェクトに格納します。

  2. 具体例

  • SQL文を自動修正し、結果セットのサイズ制限を追加。
  • 総レコード数を自動取得し、Pageオブジェクトにまとめ、フロントエンドでのページング表示を容易にします。
  • 開発者は手動でページングロジックを書く必要がなく、開発効率が向上します。

要するに、適切なインターセプタを設定し、サービス層で分頁メソッドを呼び出すことで、分頁機能が透明に動作します。

さらに、MyBatis Plusの分頁機能を利用するには、必ずPageInterceptorCustomを注入する必要があります。このプラグインは、すべてのクエリ操作をインターセプトし、必要な場合はSQLを自動修正します。

例えば、次のようなコードで分頁機能を有効にします。

@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PageInterceptorCustom(DbType.POSTGRESQL)); // 実際のDBタイプに応じて変更
        return interceptor;
    }
}

このコードによって、分頁プラグインがデータベース操作をインターセプトし、必要な場合にSQLを修正します。

最後に、MyBatis Plusの分頁処理の核心となるpageメソッドについて説明します。

public class ProductServiceImpl extends ServiceImpl<ProductDao, ProductEntity> implements ProductService {

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long categoryId) {
        IPage<ProductEntity> page = this.page(
            new Query<ProductEntity>().getPage(params),
            wrapper
        );
        ...
    }
}

このコードでは:

  • this.page(...)メソッドは、現在のサービスクラスのインスタンスにより、分頁クエリを実行します。
  • new Query<ProductEntity>().getPage(params)は、ページリクエスト情報を生成します。
  • wrapperはクエリ条件を定義し、これに基づいて分頁結果を返します。

以上が、Spring BootとVue.jsプロジェクトにおけるMyBatis Plusの分頁機能に関する詳細です。

タグ: Spring Boot vue.js MyBatis Plus pagination Java

7月15日 23:00 投稿