Mybatis:PageHelper分页插件源码及原理剖析

开发 后端
我们将简单介绍PageHelper的基本使用和配置参数的含义,重点分析PageHelper作为Mybatis分页插件的实现原理。

PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件,其实我并不想加上好用两个字,但是为了表扬插件作者开源免费的崇高精神,我毫不犹豫的加上了好用一词作为赞美。

原本以为分页插件,应该是很简单的,然而PageHelper比我想象的要复杂许多,它做的很强大,也很彻底,强大到使用者可能并不需要这么多功能,彻底到一参可以两用。但是,我认为,作为分页插件,完成物理分页任务是根本,其它的很多智能并不是必要的,保持它够傻够憨,专业术语叫stupid,简单就是美。

我们将简单介绍PageHelper的基本使用和配置参数的含义,重点分析PageHelper作为Mybatis分页插件的实现原理。

1. PageHelper的maven依赖及插件配置 

  1. <dependency>  
  2.     <groupId>com.github.pagehelper</groupId>  
  3.     <artifactId>pagehelper</artifactId>  
  4.     <version>4.1.6</version>  
  5. </dependency> 

PageHelper除了本身的jar包外,它还依赖了一个叫jsqlparser的jar包,使用时,我们不需要单独指定jsqlparser的maven依赖,maven的间接依赖会帮我们引入。 

  1. <!-- com.github.pagehelper为PageHelper类所在包名 -->  
  2. <plugin interceptor="com.github.pagehelper.PageHelper">  
  3.     <property name="dialect" value="mysql" />  
  4.     <!-- 该参数默认为false -->  
  5.     <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->  
  6.     <!-- 和startPage中的pageNum效果一样 -->  
  7.     <property name="offsetAsPageNum" value="false" />  
  8.     <!-- 该参数默认为false -->  
  9.     <!-- 设置为true时,使用RowBounds分页会进行count查询 -->  
  10.     <property name="rowBoundsWithCount" value="true" />  
  11.     <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->  
  12.     <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型) <property name="pageSizeZero" value="true"/> -->  
  13.     <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->  
  14.     <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->  
  15.     <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->  
  16.     <property name="reasonable" value="true" />  
  17.     <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->  
  18.     <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->  
  19.     <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 -->  
  20.     <!-- 不理解该含义的前提下,不要随便复制该配置 <property name="params" value="pageNum=start;pageSize=limit;"/> -->  
  21. </plugin> 

上面是PageHelper官方给的配置和注释,虽然写的很多,不过确实描述的很明白。

  •   dialect:标识是哪一种数据库,设计上必须。
  •   offsetAsPageNum:将RowBounds第一个参数offset当成pageNum页码使用,这就是上面说的一参两用,个人觉得完全没必要,offset = pageSize * pageNum就搞定了,何必混用参数呢?
  •   rowBoundsWithCount:设置为true时,使用RowBounds分页会进行count查询,个人觉得完全没必要,实际开发中,每一个列表分页查询,都配备一个count数量查询即可。
  •   reasonable:value=true时,pageNum小于1会查询第一页,如果pageNum大于pageSize会查询最后一页 ,个人认为,参数校验在进入Mybatis业务体系之前,就应该完成了,不可能到达Mybatis业务体系内参数还带有非法的值。

这么一来,我们只需要记住 dialect = mysql 一个参数即可,其实,还有下面几个相关参数可以配置。

  •   autoDialect:true or false,是否自动检测dialect。
  •   autoRuntimeDialect:true or false,多数据源时,是否自动检测dialect。
  •   closeConn:true or false,检测完dialect后,是否关闭Connection连接。

上面这3个智能参数,不到万不得已,我们不应该在系统中使用,我们只需要一个dialect = mysql 或者 dialect = oracle就够了,如果系统中需要使用,还是得问问自己,是否真的非用不可。

2. PageHelper源码分析 

  1. @Intercepts(@Signature(type = Executor.class, method = "query"args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))  
  2. public class PageHelper implements Interceptor {  
  3.     //sql工具类  
  4.     private SqlUtil sqlUtil;  
  5.     //属性参数信息  
  6.     private Properties properties;  
  7.     //配置对象方式  
  8.     private SqlUtilConfig sqlUtilConfig;  
  9.     //自动获取dialect,如果没有setProperties或setSqlUtilConfig,也可以正常进行  
  10.     private boolean autoDialect = true 
  11.     //运行时自动获取dialect  
  12.     private boolean autoRuntimeDialect;  
  13.     //多数据源时,获取jdbcurl后是否关闭数据源  
  14.     private boolean closeConn = true 
  15.     //缓存  
  16.     private Map<String, SqlUtil> urlSqlUtilMap = new ConcurrentHashMap<String, SqlUtil>();  
  17.     private ReentrantLock lock = new ReentrantLock();  
  18. // ...  

上面是官方源码以及源码所带的注释,我们再补充一下。

SqlUtil:数据库类型专用sql工具类,一个数据库url对应一个SqlUtil实例,SqlUtil内有一个Parser对象,如果是mysql,它是MysqlParser,如果是oracle,它是OracleParser,这个Parser对象是SqlUtil不同实例的主要存在价值。执行count查询、设置Parser对象、执行分页查询、保存Page分页对象等功能,均由SqlUtil来完成。

SqlUtilConfig:Spring Boot中使用,忽略。

autoRuntimeDialect:多个数据源切换时,比如mysql和oracle数据源同时存在,就不能简单指定dialect,这个时候就需要运行时自动检测当前的dialect。

Map<String, SqlUtil> urlSqlUtilMap:它就用来缓存autoRuntimeDialect自动检测结果的,key是数据库的url,value是SqlUtil。由于这种自动检测只需要执行1次,所以做了缓存。

ReentrantLock lock:这个lock对象是比较有意思的现象,urlSqlUtilMap明明是一个同步ConcurrentHashMap,又搞了一个lock出来同步ConcurrentHashMap做什么呢?是否是画蛇添足?

在《Java并发编程实战》一书中有详细论述,简单的说,ConcurrentHashMap可以保证put或者remove方法一定是线程安全的,但它不能保证put、get、remove的组合操作是线程安全的,为了保证组合操作也是线程安全的,所以使用了lock。

com.github.pagehelper.PageHelper.java源码。 

  1. // Mybatis拦截器方法   
  2.   public Object intercept(Invocation invocation) throws Throwable {  
  3.        if (autoRuntimeDialect) {  
  4.            // 多数据源  
  5.            SqlUtil sqlUtil = getSqlUtil(invocation);  
  6.            return sqlUtil.processPage(invocation);  
  7.        } else {  
  8.            // 单数据源  
  9.            if (autoDialect) {  
  10.                initSqlUtil(invocation);  
  11.            }  
  12.            // 指定了dialect  
  13.            return sqlUtil.processPage(invocation);  
  14.        }  
  15.    }  
  16.    public synchronized void initSqlUtil(Invocation invocation) {  
  17.        if (this.sqlUtil == null) {  
  18.            this.sqlUtil = getSqlUtil(invocation);  
  19.            if (!autoRuntimeDialect) {  
  20.                properties = null 
  21.                sqlUtilConfig = null 
  22.            }  
  23.            autoDialect = false 
  24.        }  
  25.    }  
  26.    public void setProperties(Properties p) {  
  27.        checkVersion();  
  28.        //多数据源时,获取jdbcurl后是否关闭数据源  
  29.        String closeConn = p.getProperty("closeConn");  
  30.        //解决#97  
  31.        if(StringUtil.isNotEmpty(closeConn)){  
  32.            this.closeConn = Boolean.parseBoolean(closeConn);  
  33.        }  
  34.        //初始化SqlUtil的PARAMS  
  35.        SqlUtil.setParams(p.getProperty("params"));  
  36.        //数据库方言  
  37.        String dialect = p.getProperty("dialect");  
  38.        String runtimeDialect = p.getProperty("autoRuntimeDialect"); 
  39.        if (StringUtil.isNotEmpty(runtimeDialect) && runtimeDialect.equalsIgnoreCase("TRUE")) {  
  40.            this.autoRuntimeDialect = true 
  41.            this.autoDialect = false 
  42.            this.properties = p;  
  43.        } else if (StringUtil.isEmpty(dialect)) {  
  44.            autoDialect = true 
  45.            this.properties = p;  
  46.        } else {  
  47.            autoDialect = false 
  48.            sqlUtil = new SqlUtil(dialect);  
  49.            sqlUtil.setProperties(p);  
  50.        }  
  51.    }  
  52.    public SqlUtil getSqlUtil(Invocation invocation) {  
  53.        MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; 
  54.        //改为对dataSource做缓存  
  55.        DataSource dataSource = ms.getConfiguration().getEnvironment().getDataSource();  
  56.        String url = getUrl(dataSource);  
  57.        if (urlSqlUtilMap.containsKey(url)) {  
  58.            return urlSqlUtilMap.get(url);  
  59.        }  
  60.        try {  
  61.            lock.lock();  
  62.            if (urlSqlUtilMap.containsKey(url)) {  
  63.                return urlSqlUtilMap.get(url);  
  64.            }  
  65.            if (StringUtil.isEmpty(url)) {  
  66.                throw new RuntimeException("无法自动获取jdbcUrl,请在分页插件中配置dialect参数!");  
  67.            }  
  68.            String dialect = Dialect.fromJdbcUrl(url);  
  69.            if (dialect == null) {  
  70.                throw new RuntimeException("无法自动获取数据库类型,请通过dialect参数指定!");  
  71.            }  
  72.            SqlUtil sqlUtil = new SqlUtil(dialect);  
  73.            if (this.properties != null) {  
  74.                sqlUtil.setProperties(properties);  
  75.            } else if (this.sqlUtilConfig != null) {  
  76.                sqlUtil.setSqlUtilConfig(this.sqlUtilConfig);  
  77.            }  
  78.            urlSqlUtilMap.put(url, sqlUtil);  
  79.            return sqlUtil;  
  80.        } finally {  
  81.            lock.unlock();  
  82.        }  
  83.    } 
  •   autoRuntimeDialect:多数据源,会创建多个SqlUtil。
  •   autoDialect:单数据源,只会创建1个SqlUtil。单数据源时,也可以当做多数据源来使用。
  •   指定了dialect:只会创建1个SqlUtil。

3. PageSqlSource 

  1. public abstract class PageSqlSource implements SqlSource {  
  2.  /**  
  3.      * 获取正常的BoundSql  
  4.      *  
  5.      * @param parameterObject  
  6.      * @return  
  7.      */  
  8.     protected abstract BoundSql getDefaultBoundSql(Object parameterObject);  
  9.     /**  
  10.      * 获取Count查询的BoundSql  
  11.      *  
  12.      * @param parameterObject  
  13.      * @return  
  14.      */  
  15.     protected abstract BoundSql getCountBoundSql(Object parameterObject);  
  16.     /**  
  17.      * 获取分页查询的BoundSql  
  18.      *  
  19.      * @param parameterObject  
  20.      * @return  
  21.      */  
  22.     protected abstract BoundSql getPageBoundSql(Object parameterObject);  
  23.     /**  
  24.      * 获取BoundSql  
  25.      *  
  26.      * @param parameterObject  
  27.      * @return  
  28.      */  
  29.     @Override  
  30.     public BoundSql getBoundSql(Object parameterObject) {  
  31.         Boolean count = getCount();  
  32.         if (count == null) {  
  33.             return getDefaultBoundSql(parameterObject);  
  34.         } else if (count) {  
  35.             return getCountBoundSql(parameterObject);  
  36.         } else {  
  37.             return getPageBoundSql(parameterObject);  
  38.         }  
  39.     }  
  •   getDefaultBoundSql:获取原始的未经改造的BoundSql。
  •   getCountBoundSql:不需要写count查询,插件根据分页查询sql,智能的为你生成的count查询BoundSql。
  •   getPageBoundSql:获取分页查询的BoundSql。

举例:

DefaultBoundSql:

  1. select  stud_id as studId , name, email, dob, phone from students 

CountBoundSql:

  1. select  count(0) from students --由PageHelper智能完成 

PageBoundSql: 

  1. select  stud_id as studId , name, email, dob, phone from students limit ?, ? 

 

  1. public class PageStaticSqlSource extends PageSqlSource {  
  2.     private String sql;  
  3.     private List<ParameterMapping> parameterMappings;  
  4.     private Configuration configuration;  
  5.     private SqlSource original;  
  6.     @Override  
  7.     protected BoundSql getDefaultBoundSql(Object parameterObject) {  
  8.         String tempSql = sql 
  9.         String orderBy = PageHelper.getOrderBy();  
  10.         if (orderBy != null) {  
  11.             tempSql = OrderByParser.converToOrderBySql(sql, orderBy);  
  12.         }  
  13.         return new BoundSql(configuration, tempSql, parameterMappings, parameterObject);  
  14.     }  
  15.     @Override  
  16.     protected BoundSql getCountBoundSql(Object parameterObject) {  
  17.         // localParser指的就是MysqlParser或者OracleParser  
  18.         // localParser.get().getCountSql(sql),可以根据原始的sql,生成一个count查询的sql  
  19.         return new BoundSql(configuration, localParser.get().getCountSql(sql), parameterMappings, parameterObject);  
  20.     }  
  21.     @Override  
  22.     protected BoundSql getPageBoundSql(Object parameterObject) {  
  23.         String tempSql = sql 
  24.         String orderBy = PageHelper.getOrderBy();  
  25.         if (orderBy != null) {  
  26.             tempSql = OrderByParser.converToOrderBySql(sql, orderBy);  
  27.         }  
  28.         // getPageSql可以根据原始的sql,生成一个带有分页参数信息的sql,比如 limit ?, ?  
  29.         tempSql = localParser.get().getPageSql(tempSql);  
  30.         // 由于sql增加了分页参数的?号占位符,getPageParameterMapping()就是在原有List<ParameterMapping>基础上,增加两个分页参数对应的ParameterMapping对象,为分页参数赋值使用  
  31.         return new BoundSql(configuration, tempSql, localParser.get().getPageParameterMapping(configuration, original.getBoundSql(parameterObject)), parameterObject); 
  32.      }  

假设List<ParameterMapping>原来的size=2,添加分页参数后,其size=4,具体增加多少个,看分页参数的?号数量。

其他PageSqlSource,原理和PageStaticSqlSource一模一样。

解析sql,并增加分页参数占位符,或者生成count查询的sql,都依靠Parser来完成。

4. com.github.pagehelper.parser.Parser

 

  1. public class MysqlParser extends AbstractParser {  
  2.     @Override  
  3.     public String getPageSql(String sql) {  
  4.         StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);  
  5.         sqlBuilder.append(sql);  
  6.         sqlBuilder.append(" limit ?,?");  
  7.         return sqlBuilder.toString();  
  8.     }  
  9.     @Override  
  10.     public Map<String, Object> setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page<?> page) {  
  11.         Map<String, Object> paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);  
  12.         paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());  
  13.         paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());  
  14.         return paramMap;  
  15.     }  

我们可以清楚的看到,MysqlParser是如何添加分页占位符和分页参数的。 

  1. public abstract class AbstractParser implements Parser, Constant {  
  2.     public String getCountSql(final String sql) {  
  3.         return sqlParser.getSmartCountSql(sql);  
  4.     }  

生成count sql,则是前文提到的jsqlparser工具包来完成的,是另外一个开源的sql解析工具包。

5. SqlUtil.doProcessPage()分页查询 

  1. // PageSqlSource装饰原SqlSource   
  2. public void processMappedStatement(MappedStatement ms) throws Throwable {  
  3.         SqlSource sqlSource = ms.getSqlSource();  
  4.         MetaObject msObject = SystemMetaObject.forObject(ms);  
  5.         SqlSource pageSqlSource;  
  6.         if (sqlSource instanceof StaticSqlSource) {  
  7.             pageSqlSource = new PageStaticSqlSource((StaticSqlSource) sqlSource);  
  8.         } else if (sqlSource instanceof RawSqlSource) {  
  9.             pageSqlSource = new PageRawSqlSource((RawSqlSource) sqlSource);  
  10.         } else if (sqlSource instanceof ProviderSqlSource) {  
  11.             pageSqlSource = new PageProviderSqlSource((ProviderSqlSource) sqlSource);  
  12.         } else if (sqlSource instanceof DynamicSqlSource) {  
  13.             pageSqlSource = new PageDynamicSqlSource((DynamicSqlSource) sqlSource);  
  14.         } else {  
  15.             throw new RuntimeException("无法处理该类型[" + sqlSource.getClass() + "]的SqlSource");  
  16.         }  
  17.         msObject.setValue("sqlSource", pageSqlSource);  
  18.         //由于count查询需要修改返回值,因此这里要创建一个Count查询的MS  
  19.         msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms));  
  20.     }  
  21. // 执行分页查询  
  22. private Page doProcessPage(Invocation invocation, Page page, Object[] args) throws Throwable {  
  23.         //保存RowBounds状态  
  24.         RowBounds rowBounds = (RowBounds) args[2];  
  25.         //获取原始的ms  
  26.         MappedStatement ms = (MappedStatement) args[0];  
  27.         //判断并处理为PageSqlSource  
  28.         if (!isPageSqlSource(ms)) {  
  29.             processMappedStatement(ms);  
  30.         }  
  31.         //设置当前的parser,后面每次使用前都会set,ThreadLocal的值不会产生不良影响  
  32.         ((PageSqlSource)ms.getSqlSource()).setParser(parser);  
  33.         try { 
  34.              //忽略RowBounds-否则会进行Mybatis自带的内存分页  
  35.             args[2] = RowBounds.DEFAULT;  
  36.             //如果只进行排序 或 pageSizeZero的判断  
  37.             if (isQueryOnly(page)) {  
  38.                 return doQueryOnly(page, invocation);  
  39.             }  
  40.             //简单的通过total的值来判断是否进行count查询  
  41.             if (page.isCount()) {  
  42.                 page.setCountSignal(Boolean.TRUE);  
  43.                 //替换MS  
  44.                 args[0] = msCountMap.get(ms.getId());  
  45.                 //查询总数  
  46.                 Object result = invocation.proceed();  
  47.                 //还原ms  
  48.                 args[0] = ms;  
  49.                 //设置总数  
  50.                 page.setTotal((Integer) ((List) result).get(0));  
  51.                 if (page.getTotal() == 0) {  
  52.                     return page;  
  53.                 }  
  54.             } else {  
  55.                 page.setTotal(-1l);  
  56.             }  
  57.             //pageSize>0的时候执行分页查询,pageSize<=0的时候不执行相当于可能只返回了一个count  
  58.             if (page.getPageSize() > 0 &&  
  59.                     ((rowBounds == RowBounds.DEFAULT && page.getPageNum() > 0)  
  60.                             || rowBounds != RowBounds.DEFAULT)) {  
  61.                 //将参数中的MappedStatement替换为新的qs  
  62.                 page.setCountSignal(null);  
  63.                 BoundSql boundSql = ms.getBoundSql(args[1]);  
  64.                 args[1] = parser.setPageParameter(ms, args[1], boundSql, page);  
  65.                 page.setCountSignal(Boolean.FALSE);  
  66.                 //执行分页查询  
  67.                 Object result = invocation.proceed();  
  68.                 //得到处理结果  
  69.                 page.addAll((List) result);  
  70.             }  
  71.         } finally {  
  72.             ((PageSqlSource)ms.getSqlSource()).removeParser();  
  73.         }  
  74.         //返回结果  
  75.         return page;  
  76.     } 

源码中注意关键的四点即可:

1、msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms)),创建count查询的MappedStatement对象,并缓存于msCountMap。

2、如果count=true,则执行count查询,结果total值保存于page对象中,继续执行分页查询。

3、执行分页查询,将查询结果保存于page对象中,page是一个ArrayList对象。

4、args[2] = RowBounds.DEFAULT,改变Mybatis原有分页行为;

args[1] = parser.setPageParameter(ms, args[1], boundSql, page),改变原有参数列表(增加分页参数)。

6. PageHelper的两种使用方式

第一种、直接通过RowBounds参数完成分页查询 。 

  1. List<Student> list = studentMapper.find(new RowBounds(0, 10));  
  2. Page page = ((Page) list; 

第二种、PageHelper.startPage()静态方法 

  1. //获取第1页,10条内容,默认查询总数count  
  2.     PageHelper.startPage(1, 10);  
  3. //紧跟着的第一个select方法会被分页  
  4.     List<Country> list = studentMapper.find();  
  5.     Page page = ((Page) list; 

注:返回结果list,已经是Page对象,Page对象是一个ArrayList。

原理:使用ThreadLocal来传递和保存Page对象,每次查询,都需要单独设置PageHelper.startPage()方法。 

  1. public class SqlUtil implements Constant {  
  2.     private static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();  

本文中经常提到的count查询,其实是PageHelper帮助我们生成的一个MappedStatement内存对象,它可以免去我们在XXXMapper.xml内单独声明一个sql count查询,我们只需要写一个sql分页业务查询即可。 

 

责任编辑:庞桂玉 来源: Java知音
相关推荐

2021-08-09 11:15:28

MybatisJavaSpring

2020-12-17 08:02:42

MyBatis插件框架

2024-03-05 18:27:43

2024-04-02 08:58:13

2023-01-17 09:13:08

Mybatis后端框架

2020-12-18 08:03:00

插件MyBatis Executor

2021-07-20 10:26:53

源码底层ArrayList

2020-10-27 14:15:42

SpringBoot

2012-02-08 10:37:42

Java反射

2019-11-27 14:41:50

Java技术语言

2016-09-02 12:34:52

2024-01-19 12:48:00

Redis存储数据库

2023-04-28 08:30:56

MyBatis架构API

2021-04-15 09:07:52

hotspotJavaC++

2021-03-06 22:41:06

内核源码CAS

2011-10-10 16:44:37

分页数据库

2023-10-30 08:16:33

数据库插件Mybatis

2022-09-27 18:56:28

ArrayList数组源代码

2016-12-19 14:35:32

Spark Strea原理剖析数据

2010-07-28 09:29:36

Flex DataGr
点赞
收藏

51CTO技术栈公众号