Mybatisでページングを実装する方法

システム開発Tips

Mybatisで簡単ページ処理を実装だ!

Mybatis-PageHelperというプラグインを実装を使いましょう。
恐ろしいほど簡単にページネーションが実現出来ます。

Google先生に聞いてみても検索結果は代替中国か英語圏。
日本で全然使われてないのはなぜなんだろう。。。

え・・・そういうことなのかな?

まぁそういうことになったらおとなしく諦めましょう。
https://github.com/pagehelper/Mybatis-PageHelper

使い方もHow to useを見ると簡単です。

STEP 1. 導入

PageHelperを使用するには、pagehelper-x.y.z.jarファイルとjsqlparser-x.y.z.jarファイルをクラスパスに含める必要があります。

Mavenを使用している場合は、pom.xmlに次の依存関係を追加するだけです。

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>x.x.x</version>
</dependency>

pom.xmlに記載するときのバージョンは以下で確かめましょう。
https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper

STEP 2. PageHelperの設定方法

mybatis-config.xmlにPageHelperを記述しましょう。

<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- config params as the following -->
        <property name="param1" value="value1"/>
    </plugin>
</plugins>

Springの設定ファイル(application.xml)へ記述しましょう。
org.mybatis.spring.SqlSessionFactoryBeanへPageHelperのInterceptorを設定しましょう。

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <!-- other configuration -->
  <property name="plugins">
    <array>
      <bean class="com.github.pagehelper.PageInterceptor">
        <property name="properties">
          <!-- config params as the following -->
          <value>
            param1=value1
          </value>
        </property>
      </bean>
    </array>
  </property>
</bean>

STEP 3. コードでの使用方法

PageHelperは、色々な使い方をサポートしています。
今回ご紹介するのは、一番簡単そうなstaticメソッドを使うパターンです。

//2. use static method startPage
PageHelper.startPage(1, 10);
List<User> list = userMapper.selectByExample(new UserExample());

//3. use static method offsetPage
PageHelper.offsetPage(1, 10);
List<User> list = userMapper.selectByExample(new UserExample());

上記の様に使用するとlistには絞り込まれた結果が返って来ています。
恐ろしいですよね。これ。

また、ページ情報は意味不明ですがlistからページ情報を取得できます。

PageInfo page = new PageInfo(list);
page.getPageNum();
page.getPageSize();
page.getStartRow();
page.getEndRow();
page.getTotal();
page.getPages();
page.getFirstPage();
page.getLastPage();
page.isFirstPage();
page.isLastPage();
page.isHasPreviousPage();
page.isHasNextPage();

フォローお願いします!

コメント

タイトルとURLをコピーしました