PageHelper:簡述對物理分頁插件PageHelper的認識

PageHelper是一款好用的,開源的,免費的Mybatis第三方物理分頁插件。本文簡單介紹PageHelper的基本使用和配置參數的含義,重點分析PageHelper作爲Mybatis分頁插件的實現原理。GitHub地址爲:https://github.com/pagehelper/Mybatis-PageHelper

一、PageHelper的maven依賴及插件配置

PageHelper除了本身的jar包外,它還依賴了一個叫jsqlparser的jar包,使用時,我們不需要單獨指定jsqlparser的maven依賴,maven的間接依賴會幫我們引入。

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

PageHelper官方給的配置和註釋如下:

  • dialect:標識是哪一種數據庫,必須
  • offsetAsPageNum:將RowBounds第一個參數offset當成pageNum頁碼使用,即一參兩用。非必需,offset = pageSize * pageNum就搞定了,不需要混用參數!
  • rowBoundsWithCount:設置爲true時,使用RowBounds分頁會進行count查詢,非必需,實際開發中,每一個列表分頁查詢,都配備一個count數量查詢即可。
  • reasonable:value=true時,pageNum小於1會查詢第一頁,如果pageNum大於pageSize會查詢最後一頁 。
  • autoDialect:true or false,是否自動檢測dialect。智能參數,一般不配置。
  • autoRuntimeDialect:true or false,多數據源時,是否自動檢測dialect。智能參數,一般不配置。
  • closeConn:true or false,檢測完dialect後,是否關閉Connection連接。智能參數,一般不配置。
<!-- com.github.pagehelper爲PageHelper類所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
    <property name="dialect" value="mysql" />
    
    <!-- 該參數默認爲false -->
    <!-- 設置爲true時,會將RowBounds第一個參數offset當成pageNum頁碼使用,和startPage中的pageNum效果一樣 -->
    <property name="offsetAsPageNum" value="false" />
    
    <!-- 該參數默認爲false -->
    <!-- 設置爲true時,使用RowBounds分頁會進行count查詢 -->
    <property name="rowBoundsWithCount" value="true" />
    
    <!-- 設置爲true時,如果pageSize=0或者RowBounds.limit = 0就會查詢出全部的結果 (相當於沒有執行分頁查詢,但是返回結果仍然是Page類型)-->
    <!-- 
    <property name="pageSizeZero" value="true"/>
    -->
     
    <!-- 3.3.0版本可用 - 分頁參數合理化,默認false禁用 -->
    <!-- 啓用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最後一頁 -->
    <!-- 禁用合理化時,如果pageNum<1或pageNum>pages會返回空數據 -->
    <property name="reasonable" value="true" />
    
    <!-- 3.5.0版本可用 - 爲了支持startPage(Object params)方法 -->
    <!-- 增加了一個`params`參數來配置參數映射,用於從Map或ServletRequest中取值 -->
    <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默認值 -->
    <!-- 
    <property name="params" value="pageNum=start;pageSize=limit;"/>
    -->
</plugin>

二、PageHelper源碼分析 - PageHelper

PageHelper官方源碼以及源碼所帶的註釋如下:

@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class PageHelper implements Interceptor {
    //sql工具類
    private SqlUtil sqlUtil;
    //屬性參數信息
    private Properties properties;
    //配置對象方式
    private SqlUtilConfig sqlUtilConfig;
    //自動獲取dialect,如果沒有setProperties或setSqlUtilConfig,也可以正常進行
    private boolean autoDialect = true;
    //運行時自動獲取dialect
    private boolean autoRuntimeDialect;
    //多數據源時,獲取jdbcurl後是否關閉數據源
    private boolean closeConn = true;
    //緩存
    private Map<String, SqlUtil> urlSqlUtilMap = new ConcurrentHashMap<String, SqlUtil>();
    private ReentrantLock lock = new ReentrantLock();
    
    ......
}

   // Mybatis攔截器方法 
   public Object intercept(Invocation invocation) throws Throwable {
        if (autoRuntimeDialect) {
            // 多數據源
            SqlUtil sqlUtil = getSqlUtil(invocation);
            return sqlUtil.processPage(invocation);
        } else {
            // 單數據源
            if (autoDialect) {
                initSqlUtil(invocation);
            }
            // 指定了dialect
            return sqlUtil.processPage(invocation);
        }
    }
    public synchronized void initSqlUtil(Invocation invocation) {
        if (this.sqlUtil == null) {
            this.sqlUtil = getSqlUtil(invocation);
            if (!autoRuntimeDialect) {
                properties = null;
                sqlUtilConfig = null;
            }
            autoDialect = false;
        }
    }
    public void setProperties(Properties p) {
        checkVersion();
        //多數據源時,獲取jdbcurl後是否關閉數據源
        String closeConn = p.getProperty("closeConn");
        //解決#97
        if(StringUtil.isNotEmpty(closeConn)){
            this.closeConn = Boolean.parseBoolean(closeConn);
        }
        //初始化SqlUtil的PARAMS
        SqlUtil.setParams(p.getProperty("params"));
        //數據庫方言
        String dialect = p.getProperty("dialect");
        String runtimeDialect = p.getProperty("autoRuntimeDialect");
        if (StringUtil.isNotEmpty(runtimeDialect) && runtimeDialect.equalsIgnoreCase("TRUE")) {
            this.autoRuntimeDialect = true;
            this.autoDialect = false;
            this.properties = p;
        } else if (StringUtil.isEmpty(dialect)) {
            autoDialect = true;
            this.properties = p;
        } else {
            autoDialect = false;
            sqlUtil = new SqlUtil(dialect);
            sqlUtil.setProperties(p);
        }
    }

    public SqlUtil getSqlUtil(Invocation invocation) {
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        //改爲對dataSource做緩存
        DataSource dataSource = ms.getConfiguration().getEnvironment().getDataSource();
        String url = getUrl(dataSource);
        if (urlSqlUtilMap.containsKey(url)) {
            return urlSqlUtilMap.get(url);
        }
        try {
            lock.lock();
            if (urlSqlUtilMap.containsKey(url)) {
                return urlSqlUtilMap.get(url);
            }
            if (StringUtil.isEmpty(url)) {
                throw new RuntimeException("無法自動獲取jdbcUrl,請在分頁插件中配置dialect參數!");
            }
            String dialect = Dialect.fromJdbcUrl(url);
            if (dialect == null) {
                throw new RuntimeException("無法自動獲取數據庫類型,請通過dialect參數指定!");
            }
            SqlUtil sqlUtil = new SqlUtil(dialect);
            if (this.properties != null) {
                sqlUtil.setProperties(properties);
            } else if (this.sqlUtilConfig != null) {
                sqlUtil.setSqlUtilConfig(this.sqlUtilConfig);
            }
            urlSqlUtilMap.put(url, sqlUtil);
            return sqlUtil;
        } finally {
            lock.unlock();
        }
    }
  • 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:雖然urlSqlUtilMap是一個同步ConcurrentHashMap,但是使用一個lock同步ConcurrentHashMap是有必要的。在《Java併發編程實戰》一書中有詳細論述,簡單的說,ConcurrentHashMap可以保證put或者remove方法一定是線程安全的,但它不能保證put、get、remove的組合操作是線程安全的,爲了保證組合操作也是線程安全的,所以使用了lock。

補充:

  • autoRuntimeDialect:多數據源,會創建多個SqlUtil。

  • autoDialect:單數據源,只會創建1個SqlUtil。單數據源時,也可以當做多數據源來使用。

  • < property name=“dialect” value=“mysql” /> 指定了dialect:只會創建1個SqlUtil。

三、PageHelper源碼分析 - SqlSource

在這裏插入圖片描述

3.1 PageSqlSource

public abstract class PageSqlSource implements SqlSource {
 /**
     * 獲取正常的BoundSql
     *
     * @param parameterObject
     * @return
     */
    protected abstract BoundSql getDefaultBoundSql(Object parameterObject);/**
     * 獲取Count查詢的BoundSql
     * @param parameterObject
     * @return
     */
    protected abstract BoundSql getCountBoundSql(Object parameterObject);/**
     * 獲取分頁查詢的BoundSql
     * @param parameterObject
     * @return
     */
    protected abstract BoundSql getPageBoundSql(Object parameterObject);/**
     * 獲取BoundSql
     * @param parameterObject
     * @return
     */
    @Override
    public BoundSql getBoundSql(Object parameterObject) {
        Boolean count = getCount();
        if (count == null) {
            return getDefaultBoundSql(parameterObject);
        } else if (count) {
            return getCountBoundSql(parameterObject);
        } else {
            return getPageBoundSql(parameterObject);
        }
    }
}
  • getDefaultBoundSql:獲取原始的未經改造的BoundSql。
  • getCountBoundSql:不需要寫count查詢,插件根據分頁查詢sql,智能的爲你生成的count查詢BoundSql。
  • getPageBoundSql:獲取分頁查詢的BoundSql。
DefaultBoundSql:
select stud_id as studId , name, email, dob, phone from students

CountBoundSql:
select count(0) from students    --由PageHelper智能完成

PageBoundSql:
select stud_id as studId , name, email, dob, phone from students limit ?, ?

3.2 PageStaticSqlSource

public class PageStaticSqlSource extends PageSqlSource {
    private String sql;
    private List<ParameterMapping> parameterMappings;
    private Configuration configuration;
    private SqlSource original;

    @Override
    protected BoundSql getDefaultBoundSql(Object parameterObject) {
        String tempSql = sql;
        String orderBy = PageHelper.getOrderBy();
        if (orderBy != null) {
            tempSql = OrderByParser.converToOrderBySql(sql, orderBy);
        }
        return new BoundSql(configuration, tempSql, parameterMappings, parameterObject);
    }

    @Override
    protected BoundSql getCountBoundSql(Object parameterObject) {
        // localParser指的就是MysqlParser或者OracleParser
        // localParser.get().getCountSql(sql),可以根據原始的sql,生成一個count查詢的sql
        return new BoundSql(configuration, localParser.get().getCountSql(sql), parameterMappings, parameterObject);
    }

    @Override
    protected BoundSql getPageBoundSql(Object parameterObject) {
        String tempSql = sql;
        String orderBy = PageHelper.getOrderBy();
        if (orderBy != null) {
            tempSql = OrderByParser.converToOrderBySql(sql, orderBy);
        }
        // getPageSql可以根據原始的sql,生成一個帶有分頁參數信息的sql,比如 limit ?, ?
        tempSql = localParser.get().getPageSql(tempSql);
        // 由於sql增加了分頁參數的?號佔位符,getPageParameterMapping()就是在原有List<ParameterMapping>基礎上,增加兩個分頁參數對應的ParameterMapping對象,爲分頁參數賦值使用
        return new BoundSql(configuration, tempSql, localParser.get().getPageParameterMapping(configuration, original.getBoundSql(parameterObject)), parameterObject);
    }
}

< ParameterMapping >原來的size看分頁參數的?號數量。其他PageSqlSource,原理和PageStaticSqlSource一模一樣。

解析sql,並增加分頁參數佔位符,或者生成count查詢的sql,都依靠Parser來完成。

四、PageHelper源碼分析 - Parser

4.1 AbstractParser

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

4.2 AbstractParser

public class MysqlParser extends AbstractParser {
    @Override
    public String getPageSql(String sql) {
        StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
        sqlBuilder.append(sql);
        sqlBuilder.append(" limit ?,?");
        return sqlBuilder.toString();
    }

    @Override
    public Map<String, Object> setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page<?> page) {
        Map<String, Object> paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);
        paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
        paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
        return paramMap;
    }
}

從上述源碼中可以看到,MysqlParser是如何添加分頁佔位符和分頁參數的。生成count sql,則是前文提到的jsqlparser工具包來完成的,是另外一個開源的sql解析工具包。

五、PageHelper源碼分析 - SqlUtil.doProcessPage()分頁查詢

源碼中有四點需要注意的地方:

  • msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms)),
    創建count查詢的MappedStatement對象,並緩存於msCountMap。
  • 如果count=true,則執行count查詢,結果total值保存於page對象中,繼續執行分頁查詢。
  • 執行分頁查詢,將查詢結果保存於page對象中,page是一個ArrayList對象。
  • args[2] = RowBounds.DEFAULT,改變Mybatis原有分頁行爲;
    args[1] = parser.setPageParameter(ms, args[1], boundSql, page),改變原有參數列表(增加分頁參數)。
// PageSqlSource裝飾原SqlSource   
public void processMappedStatement(MappedStatement ms) throws Throwable {
        SqlSource sqlSource = ms.getSqlSource();
        MetaObject msObject = SystemMetaObject.forObject(ms);
        SqlSource pageSqlSource;
        if (sqlSource instanceof StaticSqlSource) {
            pageSqlSource = new PageStaticSqlSource((StaticSqlSource) sqlSource);
        } else if (sqlSource instanceof RawSqlSource) {
            pageSqlSource = new PageRawSqlSource((RawSqlSource) sqlSource);
        } else if (sqlSource instanceof ProviderSqlSource) {
            pageSqlSource = new PageProviderSqlSource((ProviderSqlSource) sqlSource);
        } else if (sqlSource instanceof DynamicSqlSource) {
            pageSqlSource = new PageDynamicSqlSource((DynamicSqlSource) sqlSource);
        } else {
            throw new RuntimeException("無法處理該類型[" + sqlSource.getClass() + "]的SqlSource");
        }
        msObject.setValue("sqlSource", pageSqlSource);
        //由於count查詢需要修改返回值,因此這裏要創建一個Count查詢的MS
        msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms));
    }

// 執行分頁查詢
private Page doProcessPage(Invocation invocation, Page page, Object[] args) throws Throwable {
        //保存RowBounds狀態
        RowBounds rowBounds = (RowBounds) args[2];
        //獲取原始的ms
        MappedStatement ms = (MappedStatement) args[0];
        //判斷並處理爲PageSqlSource
        if (!isPageSqlSource(ms)) {
            processMappedStatement(ms);
        }
        //設置當前的parser,後面每次使用前都會set,ThreadLocal的值不會產生不良影響
        ((PageSqlSource)ms.getSqlSource()).setParser(parser);
        try {
            //忽略RowBounds-否則會進行Mybatis自帶的內存分頁
            args[2] = RowBounds.DEFAULT;
            //如果只進行排序 或 pageSizeZero的判斷
            if (isQueryOnly(page)) {
                return doQueryOnly(page, invocation);
            }

            //簡單的通過total的值來判斷是否進行count查詢
            if (page.isCount()) {
                page.setCountSignal(Boolean.TRUE);
                //替換MS
                args[0] = msCountMap.get(ms.getId());
                //查詢總數
                Object result = invocation.proceed();
                //還原ms
                args[0] = ms;
                //設置總數
                page.setTotal((Integer) ((List) result).get(0));
                if (page.getTotal() == 0) {
                    return page;
                }
            } else {
                page.setTotal(-1l);
            }
            //pageSize>0的時候執行分頁查詢,pageSize<=0的時候不執行相當於可能只返回了一個count
            if (page.getPageSize() > 0 &&
                    ((rowBounds == RowBounds.DEFAULT && page.getPageNum() > 0)
                            || rowBounds != RowBounds.DEFAULT)) {
                //將參數中的MappedStatement替換爲新的qs
                page.setCountSignal(null);
                BoundSql boundSql = ms.getBoundSql(args[1]);
                args[1] = parser.setPageParameter(ms, args[1], boundSql, page);
                page.setCountSignal(Boolean.FALSE);
                //執行分頁查詢
                Object result = invocation.proceed();
                //得到處理結果
                page.addAll((List) result);
            }
        } finally {
            ((PageSqlSource)ms.getSqlSource()).removeParser();
        }

        //返回結果
        return page;
    }

六、PageHelper的兩種使用方式

6.1 直接通過RowBounds參數完成分頁查詢 。

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

6.2 PageHelper.startPage()靜態方法

 //獲取第1頁,10條內容,默認查詢總數count
PageHelper.startPage(1, 10);

//緊跟着的第一個select方法會被分頁
List<Country> list = studentMapper.find();
Page page = ((Page) list;
注:返回結果list,已經是Page對象,Page對象是一個ArrayList。

原理:使用ThreadLocal來傳遞和保存Page對象,每次查詢,都需要單獨設置PageHelper.startPage()方法。

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

本文中經常提到的count查詢,其實是PageHelper幫助我們生成的一個MappedStatement內存對象,它可以免去我們在XXXMapper.xml內單獨聲明一個sql count查詢,我們只需要寫一個sql分頁業務查詢即可。


參考: http://my.oschina.net/zudajun/blog/745232

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