博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mybatis分页插件PageHelper简单使用
阅读量:4511 次
发布时间:2019-06-08

本文共 20784 字,大约阅读时间需要 69 分钟。

1. 引入分页插件

引入分页插件有下面2种方式,推荐使用 Maven 方式。

1). 引入 Jar 包

你可以从下面的地址中下载最新版本的 jar 包

由于使用了sql 解析工具,你还需要下载 jsqlparser.jar:

2). 使用 Maven

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

com.github.pagehelper
pagehelper
最新版本

最新版本号可以从首页查看。

 

 

2. 配置拦截器插件

  特别注意,新版拦截器是 com.github.pagehelper.PageInterceptor。 com.github.pagehelper.PageHelper 现在是一个特殊的 dialect 实现类,是分页插件的默认实现类,提供了和以前相同的用法。

 

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

使用 spring 的属性配置方式,可以使用 plugins 属性像下面这样配置:

params=value1

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
selectAllExamsByName(@Param("name")String name);

 

 

 ExamMapper.xml自己手动加的一个方法的实现:

 

 

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

 

 

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

pom.xml

4.0.0
cn.qlq
MybatisPagerHelper
0.0.1-SNAPSHOT
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.7
1.7
UTF-8
junit
junit
4.9
test
javax.servlet
servlet-api
2.5
provided
javax.servlet
jsp-api
2.0
provided
com.github.pagehelper
pagehelper
5.1.0
org.mybatis
mybatis
3.2.7
mysql
mysql-connector-java
5.1.37

 

最终的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
exams = examMapper.selectByExample(examExample); PageInfo
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
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
exams = examMapper.selectAllExamsByName("厂级"); PageInfo
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
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
exams = examMapper.selectAllExamsByName("厂级"); PageInfo
pageInfo = new PageInfo<>(exams);

   exams就是分页查出的数据,最后将数据存入pageInfo的list中,pageInfo中就是分页的全部信息,可以直接返回到页面进行显示。

 

 

 

---------------------Maven项目mysql数据库集成Spring的测试---------------

0.添加spring 的包

pom.xml

4.0.0
cn.qlq
MybatisPagerHelper
0.0.1-SNAPSHOT
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.7
1.7
UTF-8
junit
junit
4.9
test
javax.servlet
servlet-api
2.5
provided
javax.servlet
jsp-api
2.0
provided
com.github.pagehelper
pagehelper
5.1.2
org.mybatis
mybatis
3.2.7
cglib
cglib
2.2.2
org.mybatis
mybatis-spring
1.2.1
mysql
mysql-connector-java
5.1.37
org.springframework
spring-beans
4.2.4.RELEASE
org.springframework
spring-context
4.2.4.RELEASE
org.springframework
spring-test
4.2.4.RELEASE
org.springframework
spring-tx
4.2.4.RELEASE
commons-dbcp
commons-dbcp
1.3
org.springframework
spring-jdbc
4.2.4.RELEASE

 

1.修改mybatis主配置文件:

SqlMapConfig2.xml

 

2.增加spring配置文件

applicationContext.xml

helperDialect=mysql reasonable=true

 

  注意上面黄色背景的配置:(用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
exams = examMapper.selectByExample(examExample); PageInfo
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
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
exams = examMapper.selectAllExamsByName("厂级"); PageInfo
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
exams2 = examMapper.selectAllExamsByName("厂级"); //总共86条 System.out.println("第二次查询的exams2的大小"+exams2.size()); }}

 

结果:

test1:

 

 

 

 test2:

 

 

 

总结:

  在spring中配置pagehelper插件的时候要用helperDialect=mysql,用dialect=mysql会报错

 

 

git源码地址:

 

 

 

自己项目中的一个例子:(Spring+Struts2+Mybatis)

Mapper接口

 

public interface TraincontentCustomMapper {    List
> selectTraincontentWithFYCondition(Map map);}

 

 

 

Mapper实现(只用写查询,不用写分页)

 

 

 

 

 

Service接口:

 

List
> selectTraincontentWithFYCondition(Map map) throws Exception;

 

 

 

ServiceImpl实现上面方法:

 

@Override    public List
> selectTraincontentWithFYCondition(Map map) throws Exception { List
> 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
(); // 封装查询条件 Map
condition = new HashMap
();//封装条件的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
> traincontentList = traincontentService.selectTraincontentWithFYCondition(condition); PageInfo
> pageInfo = new PageInfo<>(traincontentList); /******E PageHelper分页*********/ map.put("pageInfo", pageInfo); return "ok"; }

 

 

 

传到前台的JSON数据:

 

 

 

 

 

 

补充:pageHelper也可以设置排序类别:

例如:

数据库数据:

 

 

Mapper配置:

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

 

  •  (1)根据id升序取3条

Action设置根据id升序排序,取3条

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

 

 

 

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

/**     * 开始分页     *     * @param pageNum  页码     * @param pageSize 每页显示数量     * @param orderBy  排序     */    public static 
Page
startPage(int pageNum, int pageSize, String orderBy) { Page
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, name11:25:02,941 TRACE findUsersByPage:138 - <==        Row: 1, QLQ11:25:02,943 TRACE findUsersByPage:138 - <==        Row: 2, QLQ211: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
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, name11:35:36,310 TRACE findUsersByPage:138 - <==        Row: 3, QLQ311:35:36,311 TRACE findUsersByPage:138 - <==        Row: 2, QLQ2

 

转载于:https://www.cnblogs.com/qlqwjy/p/8442148.html

你可能感兴趣的文章
Entity Framework操作Oracle数据库实现主键自增问题
查看>>
Leetcode WC-108-03 931-下降路径最小和
查看>>
从“智猪博弈”看所谓“大国责任”
查看>>
Day3:Spring-JDBC、事务管理
查看>>
模块的四种形式
查看>>
教你如何培养幽默感
查看>>
asp.net的一个简单简历缓存方法
查看>>
loj 1185(bfs)
查看>>
全排列-按从大到小-time limited
查看>>
减肥中,做个 体重三围 测量软件
查看>>
windows下命令行修改系统时间;修改系统时间的软件
查看>>
[LeetCode] 384. Shuffle an Array 数组洗牌
查看>>
最大公约数
查看>>
序列化和反序列化
查看>>
Mac上Chrome浏览器跨域解决方案
查看>>
Sublime Text 3 全程详细图文原创教程(持续更新中。。。)
查看>>
java输出重定向
查看>>
load data with matlab
查看>>
ctypes调用dll的参数问题
查看>>
微信支付接口的调用(转)
查看>>