Mybatis分頁插件PageHelper簡單使用


1. 引入分頁插件

引入分頁插件有下面2種方式,推薦使用 Maven 方式。

1). 引入 Jar 包

你可以從下面的地址中下載最新版本的 jar 包

由於使用了sql 解析工具,你還需要下載 jsqlparser.jar:

2). 使用 Maven

在 pom.xml 中添加如下依賴:

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>最新版本</version>
</dependency>

最新版本號可以從首頁查看。

 

 

2. 配置攔截器插件

  特別注意,新版攔截器是 com.github.pagehelper.PageInterceptor。 com.github.pagehelper.PageHelper 現在是一個特殊的 dialect 實現類,是分頁插件的默認實現類,提供了和以前相同的用法。

<!--
    plugins在配置文件中的位置必須符合要求,否則會報錯,順序如下:
    properties?, settings?,
    typeAliases?, typeHandlers?,
    objectFactory?,objectWrapperFactory?,
    plugins?,
    environments?, databaseIdProvider?, mappers?
-->
<plugins>
    <!-- com.github.pagehelper為PageHelper類所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- 使用下面的方式配置參數,后面會有所有的參數介紹 -->
        <property name="param1" value="value1"/>
    </plugin>
</plugins>

 

2. 在 Spring 配置文件中配置攔截器插件

使用 spring 的屬性配置方式,可以使用 plugins 屬性像下面這樣配置:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <!-- 注意其他配置 -->
  <property name="plugins">
    <array>
      <bean class="com.github.pagehelper.PageInterceptor">
        <property name="properties">
          <!--使用下面的方式配置參數,一行配置一個 -->
          <value>
            params=value1
          </value>
        </property>
      </bean>
    </array>
  </property>
</bean>

3. 分頁插件參數介紹

分頁插件提供了多個可選參數,這些參數使用時,按照上面兩種配置方式中的示例配置即可。

分頁插件可選參數如下:

  • dialect:默認情況下會使用 PageHelper 方式進行分頁,如果想要實現自己的分頁邏輯,可以實現 Dialect(com.github.pagehelper.Dialect) 接口,然后配置該屬性為實現類的全限定名稱。

下面幾個參數都是針對默認 dialect 情況下的參數。使用自定義 dialect 實現時,下面的參數沒有任何作用。

  1. helperDialect:分頁插件會自動檢測當前的數據庫鏈接,自動選擇合適的分頁方式。 你可以配置helperDialect屬性來指定分頁插件使用哪種方言。配置時,可以使用下面的縮寫值:
    oracle,mysql,mariadb,sqlite,hsqldb,postgresql,db2,sqlserver,informix,h2,sqlserver2012,derby
    特別注意:使用 SqlServer2012 數據庫時,需要手動指定為 sqlserver2012,否則會使用 SqlServer2005 的方式進行分頁。
    你也可以實現 AbstractHelperDialect,然后配置該屬性為實現類的全限定名稱即可使用自定義的實現方法。

  2. offsetAsPageNum:默認值為 false,該參數對使用 RowBounds 作為分頁參數時有效。 當該參數設置為 true 時,會將 RowBounds 中的 offset 參數當成 pageNum 使用,可以用頁碼和頁面大小兩個參數進行分頁。

  3. rowBoundsWithCount:默認值為false,該參數對使用 RowBounds 作為分頁參數時有效。 當該參數設置為true時,使用 RowBounds 分頁會進行 count 查詢。

  4. pageSizeZero:默認值為 false,當該參數設置為 true 時,如果 pageSize=0 或者 RowBounds.limit = 0 就會查詢出全部的結果(相當於沒有執行分頁查詢,但是返回結果仍然是 Page 類型)。

  5. reasonable:分頁合理化參數,默認值為false。當該參數設置為 true 時,pageNum<=0 時會查詢第一頁, pageNum>pages(超過總數時),會查詢最后一頁。默認false 時,直接根據參數進行查詢。

  6. params:為了支持startPage(Object params)方法,增加了該參數來配置參數映射,用於從對象中根據屬性名取值, 可以配置 pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默認值, 默認值為pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero

  7. supportMethodsArguments:支持通過 Mapper 接口參數來傳遞分頁參數,默認值false,分頁插件會從查詢方法的參數值中,自動根據上面 params 配置的字段中取值,查找到合適的值時就會自動分頁。 使用方法可以參考測試代碼中的 com.github.pagehelper.test.basic 包下的 ArgumentsMapTest 和 ArgumentsObjTest

  8. autoRuntimeDialect:默認值為 false。設置為 true 時,允許在運行時根據多數據源自動識別對應方言的分頁 (不支持自動選擇sqlserver2012,只能使用sqlserver),用法和注意事項參考下面的場景五

  9. closeConn:默認值為 true。當使用運行時動態數據源或沒有設置 helperDialect 屬性自動獲取數據庫類型時,會自動獲取一個數據庫連接, 通過該屬性來設置是否關閉獲取的這個連接,默認true關閉,設置為 false 后,不會關閉獲取的連接,這個參數的設置要根據自己選擇的數據源來決定。

重要提示:

當 offsetAsPageNum=false 的時候,由於 PageNum 問題,RowBounds查詢的時候 reasonable 會強制為 false。使用 PageHelper.startPage 方法不受影響。

 

 

---------------------Maven項目mysql數據庫沒有集成Spring的測試---------------

0.目錄結構:

 

1.Exam在mysql表結構

 

2.Exam.java與ExamExample.java是mybatis逆向工程導出來的:

3.ExamMapper.java是在導出來的基礎上加了一個自己寫的方法,對應mapper的xml也加了一個自己的實現:

ExamMapper.java自己手動加的一個方法:

    /**
     * 自己手寫的一個根據名字模糊查詢考試
     * @param name
     * @return
     */
    List<Exam> selectAllExamsByName(@Param("name")String name);

 

 

 ExamMapper.xml自己手動加的一個方法的實現:

  <!-- 自己手寫的一個根據名字模糊查詢考試   exam是掃描出來的別名 -->
  <select id="selectAllExamsByName" parameterType="string" resultType="exam">
      select * from exam where examName like '%${name}%'
  </select>

 

 

4.SqlMapConfig.xml配置:(注意plugins的配置)

<?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>

    <!-- 加載屬性文件 -->
    <properties resource="db.properties">
        <!--properties中還可以配置一些屬性名和屬性值 -->
        <!-- <property name="jdbc.driver" value=""/> -->
    </properties>
    <!-- 全局配置參數,需要時再設置 -->
    <!-- <settings> </settings> -->

    <!-- 別名定義 -->
    <typeAliases>

        <!-- 針對單個別名定義 type:類型的路徑 alias:別名 -->
        <!-- <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/> -->
        <!-- 批量別名定義 指定包名,mybatis自動掃描包中的po類,自動定義別名,別名就是類名(首字母大寫或小寫都可以) -->
        <package name="cn.xm.exam.bean.exam" />

    </typeAliases>

    <plugins>
        <!-- com.github.pagehelper為PageHelper類所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 使用下面的方式配置參數,后面會有所有的參數介紹 -->
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>


    <!-- 和spring整合后 environments配置將廢除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事務管理,事務控制由mybatis -->
            <transactionManager type="JDBC" />
            <!-- 數據庫連接池,由mybatis管理 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 加載 映射文件 -->
    <mappers>
        <!-- 批量加載mapper 指定mapper接口的包名,mybatis自動掃描包下邊所有mapper接口進行加載 遵循一些規范:需要將mapper接口類名和mapper.xml映射文件名稱保持一致,且在一個目錄 
            中 上邊規范的前提是:使用的是mapper代理方法 -->
        <package name="cn.xm.exam.mapper" />

    </mappers>

</configuration>

 

 

4.pom.xml配置以及項目中的jar包:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.qlq</groupId>
    <artifactId>MybatisPagerHelper</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <build>
        <!-- 配置了很多插件 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- pageHelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.0</version>
        </dependency>

        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>
        
        <!-- mysql連接驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
    </dependencies>

</project>

 

最終的jar包:

 

6.測試代碼:

package cn.xm.exam.daoTest;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.print.Doc;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.xm.exam.bean.exam.Exam;
import cn.xm.exam.bean.exam.ExamExample;
import cn.xm.exam.mapper.exam.ExamMapper;

public class PageHelperTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }


    @Test
    public void test1() {
         SqlSession sqlSession = sqlSessionFactory.openSession();
         //創建ExamMapper對象
         ExamMapper examMapper = sqlSession.getMapper(ExamMapper.class);
         
         ExamExample examExample = new ExamExample();
         ExamExample.Criteria criteria = examExample.createCriteria();
         //只對緊鄰的下一條select語句進行分頁查詢,對之后的select不起作用
         PageHelper.startPage(1,8);
         //上面pagehelper的設置對此查詢有效,查到數據總共8條
        List<Exam> exams = examMapper.selectByExample(examExample);
        PageInfo<Exam> pageInfo = new PageInfo<>(exams);
        System.out.println("第一次查詢的exams的大小:"+exams.size());
        for(Exam e:pageInfo.getList()){
            System.out.println(e);
        }
        System.out.println("分頁工具類中數據量"+pageInfo.getList().size());
        System.out.println();
        System.out.println("---------------華麗的分割線------------");
        System.out.println();
        //第二次進行查詢:上面pagehelper的設置對此查詢無效(查詢所有的數據86條)
        List<Exam> exams2 = examMapper.selectByExample(examExample);
        //總共86條
        System.out.println("第二次查詢的exams2的大小"+exams2.size());
        
    }
    /**
     * 測試自己寫的根據名稱模糊查詢考試
     */
    @Test
    public void test2() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //創建examMapper對象
        ExamMapper examMapper = sqlSession.getMapper(ExamMapper.class);

        //只對緊鄰的下一條select語句進行分頁查詢,對之后的select不起作用
        PageHelper.startPage(1,6);
        //上面pagehelper的設置對此查詢有效,查到數據,總共6條
        List<Exam> exams = examMapper.selectAllExamsByName("廠級");
        PageInfo<Exam> pageInfo = new PageInfo<>(exams);
        System.out.println("第一次查詢的exams的大小(受pageHelper影響):"+exams.size());
        for(Exam e:pageInfo.getList()){
            System.out.println(e);
        }
        System.out.println("分頁工具類中數據量"+pageInfo.getList().size());
        System.out.println();
        System.out.println("---------------華麗的分割線------------");
        System.out.println();
         //第二次進行查詢:上面pagehelper的設置對此查詢無效(查詢所有的數據34條)
        List<Exam> exams2 = examMapper.selectAllExamsByName("廠級");
        System.out.println("第二次查詢的exams2的大小(不受pageHelper影響)"+exams2.size());
        
    }
}

 

運行結果:

test1:

 

 

test2:

 

 

 

debugger打斷點查看PageInfo的信息:(也就是將來在開發過程中直接返回PageInfo對象就可以將分頁所需要的全部參數攜帶到前台)

 

 

 總結:

  使用也簡單,大致就是導包,兩個包(pagehelper和jsqlparser),然后在配置文件中引入插件,最后在代碼中使用,使用方法可以簡化成如下:

        //只對緊鄰的下一條select語句進行分頁查詢,對之后的select不起作用
        PageHelper.startPage(1,6);
        //上面pagehelper的設置對此查詢有效,查到數據,總共6條
        List<Exam> exams = examMapper.selectAllExamsByName("廠級");
        PageInfo<Exam> pageInfo = new PageInfo<>(exams);

   exams就是分頁查出的數據,最后將數據存入pageInfo的list中,pageInfo中就是分頁的全部信息,可以直接返回到頁面進行顯示。

 

 

 

---------------------Maven項目mysql數據庫集成Spring的測試---------------

0.添加spring 的包

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.qlq</groupId>
    <artifactId>MybatisPagerHelper</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <build>
        <!-- 配置了很多插件 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- pageHelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>

        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.1</version>
        </dependency>
        <!-- mysql連接驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <!-- DBCP連接池 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
    </dependencies>

    <!-- spring -->



</project>

 

1.修改mybatis主配置文件:

SqlMapConfig2.xml

<?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>
    <!-- 設置別名 -->
    <typeAliases>
        <!-- 2. 指定掃描包,會把包內所有的類都設置別名,別名的名稱就是類名,大小寫不敏感 -->
        <package name="cn.xm.exam.bean.exam" />
    </typeAliases>

</configuration>

 

2.增加spring配置文件

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


    <context:property-placeholder location="classpath:db.properties" />

    <!-- 數據庫連接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- Mybatis的工廠 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 核心配置文件的位置 -->
        <property name="configLocation" value="classpath:SqlMapConfig2.xml" />
        <!-- 注意其他配置 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置參數,一行配置一個 -->
                        <value> helperDialect=mysql reasonable=true </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!-- Mapper動態代理開發 掃描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 基本包 -->
        <property name="basePackage" value="cn.xm.exam.mapper" />
    </bean>
</beans>

 

  注意上面黃色背景的配置:(用helperDialect=mysql,用dialect=mysql會報錯)

3.最終配置文件結構:

 

 4.spring-junit測試;

 

package cn.xm.exam.daoTest;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.xm.exam.bean.exam.Exam;
import cn.xm.exam.bean.exam.ExamExample;
import cn.xm.exam.mapper.exam.ExamMapper;

/**
 * 與spring集成的mybatis的分頁插件pagehelper的測試
 * @author liqiang
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class PageHelperTestWithSpring {
    
    @Resource
    private ExamMapper examMapper;

    @Test
    public void test1() {
         //創建ExamMapper對象
         ExamExample examExample = new ExamExample();
         ExamExample.Criteria criteria = examExample.createCriteria();
         //只對緊鄰的下一條select語句進行分頁查詢,對之后的select不起作用
         PageHelper.startPage(1,8);
         //上面pagehelper的設置對此查詢有效,查到數據總共8條
        List<Exam> exams = examMapper.selectByExample(examExample);
        PageInfo<Exam> pageInfo = new PageInfo<>(exams);
        System.out.println("第一次查詢的exams的大小:"+exams.size());
        for(Exam e:pageInfo.getList()){
            System.out.println(e);
        }
        System.out.println("分頁工具類中數據量"+pageInfo.getList().size());
        System.out.println();
        System.out.println("---------------華麗的分割線------------");
        System.out.println();
        //第二次進行查詢:上面pagehelper的設置對此查詢無效(查詢所有的數據86條)
        List<Exam> exams2 = examMapper.selectByExample(examExample);
        //總共86條
        System.out.println("第二次查詢的exams2的大小"+exams2.size());
        
    }
    @Test
    public void test2() {
        //創建ExamMapper對象
        ExamExample examExample = new ExamExample();
        ExamExample.Criteria criteria = examExample.createCriteria();
        //只對緊鄰的下一條select語句進行分頁查詢,對之后的select不起作用
        PageHelper.startPage(1,8);
        //上面pagehelper的設置對此查詢有效,查到數據總共8條
        List<Exam> exams = examMapper.selectAllExamsByName("廠級");
        PageInfo<Exam> pageInfo = new PageInfo<>(exams);
        System.out.println("第一次查詢的exams的大小:"+exams.size());
        for(Exam e:pageInfo.getList()){
            System.out.println(e);
        }
        System.out.println("分頁工具類中數據量"+pageInfo.getList().size());
        System.out.println();
        System.out.println("---------------華麗的分割線------------");
        System.out.println();
        //第二次進行查詢:上面pagehelper的設置對此查詢無效(查詢所有的數據86條)
        List<Exam> exams2 = examMapper.selectAllExamsByName("廠級");
        //總共86條
        System.out.println("第二次查詢的exams2的大小"+exams2.size());
        
    }
}

 

結果:

test1:

 

 

 

 test2:

 

 

 

總結:

  在spring中配置pagehelper插件的時候要用helperDialect=mysql,用dialect=mysql會報錯

 

 

git源碼地址:https://github.com/qiao-zhi/MybatisPageHelper

 

 

 

自己項目中的一個例子:(Spring+Struts2+Mybatis)

Mapper接口

 

public interface TraincontentCustomMapper {
    List<Map<String,Object>> selectTraincontentWithFYCondition(Map map);

}

 

 

 

Mapper實現(只用寫查詢,不用寫分頁)

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.xm.exam.mapper.trainContent.custom.TraincontentCustomMapper">
    <!-- lixianyuan 9/19 start -->
    <!-- 分頁查詢:根據組合條件進行分頁查詢 -->
    <select id="selectTraincontentWithFYCondition" parameterType="map"
        resultType="map">
        select documentid,departmentid,documentname,traintype,departmentname,knowledgetype,originalname,currentname,
            uptime,size,employeename,level,description,browsetimes,typeid,typename
         from traincontent,traincontenttype
        <where>
            <if test="1 == 1">
                and traincontent.knowledgeType = traincontenttype.typeid
            </if>
            <if test="documentName!=null &amp;&amp; documentName!=''">
                and documentName like
                concat(concat('%',#{documentName}),'%')
            </if>
            <if test="departmentName!=null  &amp;&amp; departmentName!='' ">
                and departmentName like concat(concat('%',#{departmentName}),'%')
            </if>
            <if test="typeId != null">
                and knowledgeType = #{typeId}
            </if>
        </where>
        order by upTime desc
    </select>
</mapper>

 

 

 

 

Service接口:

 

List<Map<String,Object>> selectTraincontentWithFYCondition(Map map) throws Exception;

 

 

 

ServiceImpl實現上面方法:

 

    @Override
    public List<Map<String,Object>> selectTraincontentWithFYCondition(Map map) throws Exception {
        List<Map<String,Object>> trainContentList = traincontentCustomMapper.selectTraincontentWithFYCondition(map);
        if (trainContentList!=null) {
            return trainContentList;
        } else {
            return null;
        }
    }

 

 

 

Action實現分頁查詢:

    private String documentName;//文檔名稱
    private String departmentName;//部門名稱
    private String typeId;//類別編號
    
    /**
     * 根據資料名稱、所屬部門、資料級別、知識點、當前頁頁號、每頁顯示記錄數進行分頁查詢
     * 
     * @return
     * @throws Exception
     */
    public String findTrainByFYCondiction() throws Exception {
        map = new LinkedHashMap<String, Object>();
        // 封裝查詢條件
        Map<String,Object> condition = new HashMap<String,Object>();//封裝條件的map
        if(ValidateCheck.isNotNull(documentName)){
            condition.put("documentName", documentName);
        }
        if(ValidateCheck.isNotNull(departmentName)){
            condition.put("departmentName", departmentName);
        }
        if(ValidateCheck.isNotNull(typeId)){
            condition.put("typeId", typeId);
        }
        int current_page = Integer.parseInt(currentPage);//當前頁
        int current_total = Integer.parseInt(currentTotal);//頁大小
        /******S    PageHelper分頁*********/
        PageHelper.startPage(current_page,current_total);//開始分頁
        List<Map<String,Object>> traincontentList = traincontentService.selectTraincontentWithFYCondition(condition);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(traincontentList);
        /******E    PageHelper分頁*********/
        
        map.put("pageInfo", pageInfo);
        
        return "ok";
    }

 

 

 

傳到前台的JSON數據:

 

 

 

 

 

 

補充:pageHelper也可以設置排序類別:

例如:

數據庫數據:

 

 

Mapper配置:

    @Select("select * from user")
    public List<User> findUsersByPage() throws SQLException;

 

  •  (1)根據id升序取3條

Action設置根據id升序排序,取3條

    public String findPage() throws Exception {
        response = new HashMap();
        // 第三個參數代表排序方式
        PageHelper.startPage(1, 3, "id");
        List<User> users = userService.findUsersByPage();
        response.put("users", users);
        return "success";
    }

 

 

 

查看startPage(1, 3, "id")源碼:

    /**
     * 開始分頁
     *
     * @param pageNum  頁碼
     * @param pageSize 每頁顯示數量
     * @param orderBy  排序
     */
    public static <E> Page<E> startPage(int pageNum, int pageSize, String orderBy) {
        Page<E> page = startPage(pageNum, pageSize);
        page.setOrderBy(orderBy);
        return page;
    }

 

 

測試:

 

 查看日志:

11:25:02,938 DEBUG findUsersByPage:132 - ==>  Preparing: SELECT * FROM user order by id LIMIT ? 
11:25:02,939 DEBUG findUsersByPage:132 - ==> Parameters: 3(Integer)
11:25:02,941 TRACE findUsersByPage:138 - <==    Columns: id, name
11:25:02,941 TRACE findUsersByPage:138 - <==        Row: 1, QLQ
11:25:02,943 TRACE findUsersByPage:138 - <==        Row: 2, QLQ2
11:25:02,943 TRACE findUsersByPage:138 - <==        Row: 3, QLQ3

 

 

 

  • (2)根據id降序取第二頁,每頁2條

Action配置:

    public String findPage() throws Exception {
        response = new HashMap();
        // 第三個參數代表排序方式
        PageHelper.startPage(2, 2, "id desc");
        List<User> users = userService.findUsersByPage();
        response.put("users", users);
        return "success";
    }

 

 

 測試:

 

查看sql日志:

11:35:36,307 DEBUG findUsersByPage:132 - ==>  Preparing: SELECT * FROM user order by id desc LIMIT ?, ? 
11:35:36,308 DEBUG findUsersByPage:132 - ==> Parameters: 2(Integer), 2(Integer)
11:35:36,309 TRACE findUsersByPage:138 - <==    Columns: id, name
11:35:36,310 TRACE findUsersByPage:138 - <==        Row: 3, QLQ3
11:35:36,311 TRACE findUsersByPage:138 - <==        Row: 2, QLQ2

 


免責聲明!

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



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