pagehelperというMyBatisのページングプラグインはどう使うか?
MyBatisのページングプラグインであるPageHelperは、MyBatisのページング機能を実現するために使用することができるオープンソースのプラグインです。
PageHelper プラグインを使用する手順は次の通りです。
- Mavenで依存関係を追加するには、次の依存関係をプロジェクトに追加してください。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>最新版本</version>
</dependency>
- MyBatisの設定ファイルに、PageHelperプラグインの設定項目を追加します。
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<properties>
<!-- 分页参数配置 -->
<!-- dialect 属性用于配置数据库方言,默认为 mysql -->
<property name="dialect" value="mysql"/>
<!-- rowBoundsWithCount 属性用于配置是否需要查询总数,默认为 false -->
<property name="rowBoundsWithCount" value="true"/>
<!-- reasonable 属性用于配置是否启用合理化查询,默认为 false -->
<property name="reasonable" value="true"/>
</properties>
</plugin>
</plugins>
- 必要なページ分けが必要な検索方法では、PageHelper.startPage メソッドを使用してページを開始し、その後、検索クエリを実行します。
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
...
// 在查询之前调用 PageHelper.startPage 方法,传入当前页码和每页显示的数量
PageHelper.startPage(pageNum, pageSize);
// 执行查询语句
List<Entity> entities = yourMapper.yourQueryMethod();
// 使用 PageInfo 对象包装查询结果,并传入需要显示的页码数量
PageInfo<Entity> pageInfo = new PageInfo<>(entities, navigatePages);
pageNumというパラメータは現在のページ番号を表し、pageSizeというパラメータは1ページに表示される数量を表します。yourMapper.yourQueryMethod()はあなたのクエリメソッドを表します。
- ページ情報オブジェクトを使用してページングに関する情報を取得します。
// 获取当前页码
int currentPage = pageInfo.getPageNum();
// 获取每页显示的数量
int pageSize = pageInfo.getPageSize();
// 获取总记录数
long total = pageInfo.getTotal();
// 获取总页数
int pages = pageInfo.getPages();
// 获取查询结果
List<Entity> resultList = pageInfo.getList();
PageHelperプラグインを使用してページングクエリを実行できるようになります。