天天看點

Mybatis 整合Spring包,使用pageHelper插件,實作分頁查詢

十二、利用Mybatis的分頁插件實作分頁功能

方案一、利用Mybatis所提供的 RowBounds 來設定分頁參數,以該對象作為Dao方法中的參數。執行原理屬于邏輯分頁,需要把所有的記錄先查詢出來,性能有問題,一般不用。

方案二、采用實體分頁,會在SQL中使用limit關鍵字,基于逆向工程的情況下,會修改映射檔案中的語句,會造成侵入式的設計。

方案三、采用第三方的分頁插件,pageHelper,也是屬于實體分頁。

pageHelper 的使用方法

1、引入依賴
<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.1</version>
        </dependency>
           
2、在Mybatis的主配置檔案中添加pageHelper的分頁插件配置(可以在spring配置中書寫,也可以在Mybatis配置檔案中書寫)

Mybatis配置檔案:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

  <plugins>
        <!-- 引入 pageHelper插件 -->
        <!--注意這裡要寫成PageInterceptor, 5.0之前的版本都是寫PageHelper, 5.0之後要換成PageInterceptor-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!--reasonable:分頁合理化參數,預設值為false,直接根據參數進行查詢。
             當該參數設定為 true 時,pageNum<=0 時會查詢第一頁, pageNum>pages(超過總數時),會查詢最後一頁。-->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>
    
</configuration>
           
3、在查詢過程中使用分頁功能
public interface BookService {

    List<Book> findBookByExamplePageALL();

}
           
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;
    @Override
    public List<Book> findBookByExamplePageALL() {

        BookExample bookExample = new BookExample();
        BookExample.Criteria criteria = bookExample.createCriteria();
        criteria.andBooknameIsNotNull();

        //在執行查詢前,需要使用pageHelper的startPage方法
        //該方法執行後,會攔截SQL的執行,把分頁的語句織入到原有的SQL語句中
        PageHelper.startPage(1,4);
        return bookMapper.selectByExample(bookExample);
    }


}
           

官網說明,是以,可以将查詢傳回的List引用資料,直接強行轉換為Page引用類型,以擷取分頁資訊,因為查詢語句傳回的List引用資料本身就是Page類型資料。

Mybatis 整合Spring包,使用pageHelper插件,實作分頁查詢

參考目錄

pageHelper 插件 官網,描述

https://pagehelper.github.io/docs/howtouse/#3-%E5%A6%82%E4%BD%95%E5%9C%A8%E4%BB%A3%E7%A0%81%E4%B8%AD%E4%BD%BF%E7%94%A8