Mybatis從入門到精通——分頁插件pagehelper的使用(20)

一、pagehelper分頁插件

pagehelper是一個開源的基於Mybatis攔截器開發的通用分頁插件工具,一般項目中也是使用這個。

具體的項目地址:https://github.com/pagehelper/Mybatis-PageHelper

具體的使用說明:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md

注意:該插件是中國人開發的,文檔是中文的。

 

二、使用步驟:

1.引入依賴:

maven座標:

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

建議使用最新版本。

2.在Mybatis中註冊該插件,並設置默認值

    <plugin interceptor="com.github.pagehelper.PageInterceptor">
      <!--  合理分頁    -->
      <property name="reasonable" value="true"/>
    </plugin>

一般只設置一個reasonable(是否合理分頁)爲true,其它參數請參考具體文檔。

3.使用代碼:

public class MybatisTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void init() throws IOException {
        String resource = "mybatis-config.xml";
        //1.使用mybatis的工具讀取配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.創建sqlSessionFactory
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        inputStream.close();
    }

    /**
     * 測試分頁
     */
    @Test
    public void testPage() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //分頁
        Page<Object> page = PageHelper.startPage(1, 2);
        //設置查詢總數
        page.setCount(true);
        //設置排序字段
        page.setOrderBy("id desc");
        List<User> users = userMapper.selectList();
        System.out.println(users);
        //獲取總數查詢結果
        long count = page.getTotal();
        System.out.println("查詢總數:"+count);
        sqlSession.close();
    }

}

說明:

1.主要通過PageHelper的startPage方法設置要查詢的分頁(從1開始),該方法會返回一個Page,通過設置該Page的屬性可以進行分頁、排序、以及總數查詢.

2.只能通過設置PageHelper的startPage方法返回的Page才能使插件生效。

三、補充說明

1.該插件的使用非常簡單,只需要通過靜態方法設置好對應屬性即可,不需要在mapper映射文件中寫limit和order by,該插件會自動添加。

2.如果要查詢總數,總數結果只能通過返回的Page對象獲取。

3.如果存在多個mapper接口調用,則只會對第一個mapper生效,因爲使用之後會馬上清理。

4.該插件不適用於返回嵌套結果集的多表查詢,因爲Mybatis會合並其結果,導致分頁數量不準確。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章