Mybatis的分頁插件com.github.pagehelper


1. 需要引入PageHelper的jar包

  如果沒有使用maven,那直接把jar包導入到lib文件夾下即可,這個PageHelper插件在github上有開源,

地址為:https://github.com/pagehelper/Mybatis-PageHelper/tree/master/src/main/java/com/github/pagehelper。 
如果使用了maven,那么只要在pom.xml中引入該插件即可,引入如下:

<dependency>

    <groupId>com.github.pagehelper</groupId>

    <artifactId>pagehelper</artifactId>

    <version>4.1.4</version>

</dependency>

2. 在mybatis的全局配置文件SqlMapConfig.xml中配置該插件

<?xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPEconfiguration
        PUBLIC"-//mybatis.org//DTD Config 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置分頁插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 設置數據庫類型Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數據庫-->       
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>
</configuration>

3. 在執行sql前添加插件,完成分頁功能

  在查詢的sql語句執行之前,添加一行代碼PageHelper.startPage(1, 10);第一個參數表示第幾頁,第二個參數表示每頁顯示的記錄數。

這樣在執行sql后就會將記錄按照語句中設置的那樣進行分頁。如果需要獲取總記錄數的話,需要PageInfo類的對象,

這個對象可以獲取總記錄數,下面看下測試的代碼。

public class TestPageHelper {
    @Test
    public void testPageHelper() {
        // 創建一個spring容器
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*");
        // 從spring容器中獲取mapper代理對象
        TbItemMapper mapper =context.getBean(TbItemMapper.class);
        // 執行查詢並分頁,TbItemExample是逆向工程自動生成的,用來進行條件查詢,這里不設置則表示無條件
        TbItemExample example = new TbItemExample();
        //分頁處理,顯示第一頁的10條數據
        PageHelper.startPage(1, 10);
        List<TbItem> list =mapper.selectByExample(example);//查詢
        // 取商品列表
        for(TbItem item : list) {
           System.out.println(item.getTitle());
        }
        // 取分頁信息
        PageInfo<TbItem> pageInfo = new PageInfo<TbItem>(list);
        long total = pageInfo.getTotal(); //獲取總記錄數
        System.out.println("共有商品信息:" + total);
    }
}

 

官方文檔,參考:

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM