日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Mybatis:PageHelper分頁插件源碼及原理剖析

PageHelper是一款好用的開源免費的Mybatis第三方物理分頁插件,其實我并不想加上好用兩個字,但是為了表揚插件作者開源免費的崇高精神,我毫不猶豫的加上了好用一詞作為贊美。

公司主營業(yè)務(wù):成都網(wǎng)站設(shè)計、成都做網(wǎng)站、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)建站是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)建站推出漳平免費做網(wǎng)站回饋大家。

原本以為分頁插件,應(yīng)該是很簡單的,然而PageHelper比我想象的要復(fù)雜許多,它做的很強大,也很徹底,強大到使用者可能并不需要這么多功能,徹底到一參可以兩用。但是,我認(rèn)為,作為分頁插件,完成物理分頁任務(wù)是根本,其它的很多智能并不是必要的,保持它夠傻夠憨,專業(yè)術(shù)語叫stupid,簡單就是美。

我們將簡單介紹PageHelper的基本使用和配置參數(shù)的含義,重點分析PageHelper作為Mybatis分頁插件的實現(xiàn)原理。

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

 
 
 
 
  1.   
  2.     com.github.pagehelper  
  3.     pagehelper  
  4.     4.1.6  
  5.  

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

 
 
 
 
  1.   
  2.   
  3.       
  4.       
  5.       
  6.       
  7.       
  8.       
  9.       
  10.       
  11.       
  12.       
  13.       
  14.       
  15.       
  16.       
  17.       
  18.       
  19.       
  20.       
  21.  

上面是PageHelper官方給的配置和注釋,雖然寫的很多,不過確實描述的很明白。

  •   dialect:標(biāo)識是哪一種數(shù)據(jù)庫,設(shè)計上必須。
  •   offsetAsPageNum:將RowBounds第一個參數(shù)offset當(dāng)成pageNum頁碼使用,這就是上面說的一參兩用,個人覺得完全沒必要,offset = pageSize * pageNum就搞定了,何必混用參數(shù)呢?
  •   rowBoundsWithCount:設(shè)置為true時,使用RowBounds分頁會進行count查詢,個人覺得完全沒必要,實際開發(fā)中,每一個列表分頁查詢,都配備一個count數(shù)量查詢即可。
  •   reasonable:value=true時,pageNum小于1會查詢第一頁,如果pageNum大于pageSize會查詢最后一頁 ,個人認(rèn)為,參數(shù)校驗在進入Mybatis業(yè)務(wù)體系之前,就應(yīng)該完成了,不可能到達Mybatis業(yè)務(wù)體系內(nèi)參數(shù)還帶有非法的值。

這么一來,我們只需要記住 dialect = mysql 一個參數(shù)即可,其實,還有下面幾個相關(guān)參數(shù)可以配置。

  •   autoDialect:true or false,是否自動檢測dialect。
  •   autoRuntimeDialect:true or false,多數(shù)據(jù)源時,是否自動檢測dialect。
  •   closeConn:true or false,檢測完dialect后,是否關(guān)閉Connection連接。

上面這3個智能參數(shù),不到萬不得已,我們不應(yīng)該在系統(tǒng)中使用,我們只需要一個dialect = mysql 或者 dialect = oracle就夠了,如果系統(tǒng)中需要使用,還是得問問自己,是否真的非用不可。

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.     //屬性參數(shù)信息  
  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.     //多數(shù)據(jù)源時,獲取jdbcurl后是否關(guān)閉數(shù)據(jù)源  
  14.     private boolean closeConn = true;  
  15.     //緩存  
  16.     private Map urlSqlUtilMap = new ConcurrentHashMap();  
  17.     private ReentrantLock lock = new ReentrantLock();  
  18. // ...  

上面是官方源碼以及源碼所帶的注釋,我們再補充一下。

SqlUtil:數(shù)據(jù)庫類型專用sql工具類,一個數(shù)據(jù)庫url對應(yīng)一個SqlUtil實例,SqlUtil內(nèi)有一個Parser對象,如果是mysql,它是MysqlParser,如果是oracle,它是OracleParser,這個Parser對象是SqlUtil不同實例的主要存在價值。執(zhí)行count查詢、設(shè)置Parser對象、執(zhí)行分頁查詢、保存Page分頁對象等功能,均由SqlUtil來完成。

SqlUtilConfig:Spring Boot中使用,忽略。

autoRuntimeDialect:多個數(shù)據(jù)源切換時,比如mysql和oracle數(shù)據(jù)源同時存在,就不能簡單指定dialect,這個時候就需要運行時自動檢測當(dāng)前的dialect。

Map urlSqlUtilMap:它就用來緩存autoRuntimeDialect自動檢測結(jié)果的,key是數(shù)據(jù)庫的url,value是SqlUtil。由于這種自動檢測只需要執(zhí)行1次,所以做了緩存。

ReentrantLock lock:這個lock對象是比較有意思的現(xiàn)象,urlSqlUtilMap明明是一個同步ConcurrentHashMap,又搞了一個lock出來同步ConcurrentHashMap做什么呢?是否是畫蛇添足?

在《Java并發(fā)編程實戰(zhàn)》一書中有詳細論述,簡單的說,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.            // 多數(shù)據(jù)源  
  5.            SqlUtil sqlUtil = getSqlUtil(invocation);  
  6.            return sqlUtil.processPage(invocation);  
  7.        } else {  
  8.            // 單數(shù)據(jù)源  
  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.        //多數(shù)據(jù)源時,獲取jdbcurl后是否關(guān)閉數(shù)據(jù)源  
  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.        //數(shù)據(jù)庫方言  
  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參數(shù)!");  
  67.            }  
  68.            String dialect = Dialect.fromJdbcUrl(url);  
  69.            if (dialect == null) {  
  70.                throw new RuntimeException("無法自動獲取數(shù)據(jù)庫類型,請通過dialect參數(shù)指定!");  
  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:多數(shù)據(jù)源,會創(chuàng)建多個SqlUtil。
  •   autoDialect:單數(shù)據(jù)源,只會創(chuàng)建1個SqlUtil。單數(shù)據(jù)源時,也可以當(dāng)做多數(shù)據(jù)源來使用。
  •   指定了dialect:只會創(chuàng)建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:獲取原始的未經(jīng)改造的BoundSql。
  •   getCountBoundSql:不需要寫count查詢,插件根據(jù)分頁查詢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 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),可以根據(jù)原始的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可以根據(jù)原始的sql,生成一個帶有分頁參數(shù)信息的sql,比如 limit ?, ?  
  29.         tempSql = localParser.get().getPageSql(tempSql);  
  30.         // 由于sql增加了分頁參數(shù)的?號占位符,getPageParameterMapping()就是在原有List基礎(chǔ)上,增加兩個分頁參數(shù)對應(yīng)的ParameterMapping對象,為分頁參數(shù)賦值使用  
  31.         return new BoundSql(configuration, tempSql, localParser.get().getPageParameterMapping(configuration, original.getBoundSql(parameterObject)), parameterObject); 
  32.      }  

假設(shè)List原來的size=2,添加分頁參數(shù)后,其size=4,具體增加多少個,看分頁參數(shù)的?號數(shù)量。

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

解析sql,并增加分頁參數(shù)占位符,或者生成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 setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {  
  11.         Map 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是如何添加分頁占位符和分頁參數(shù)的。 

 
 
 
 
  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查詢需要修改返回值,因此這里要創(chuàng)建一個Count查詢的MS  
  19.         msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms));  
  20.     }  
  21. // 執(zhí)行分頁查詢  
  22. private Page doProcessPage(Invocation invocation, Page page, Object[] args) throws Throwable {  
  23.         //保存RowBounds狀態(tài)  
  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.         //設(shè)置當(dāng)前的parser,后面每次使用前都會set,ThreadLocal的值不會產(chǎn)生不良影響  
  32.         ((PageSqlSource)ms.getSqlSource()).setParser(parser);  
  33.         try { 
  34.              //忽略RowBounds-否則會進行Mybatis自帶的內(nèi)存分頁  
  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.                 //查詢總數(shù)  
  46.                 Object result = invocation.proceed();  
  47.                 //還原ms  
  48.                 args[0] = ms;  
  49.                 //設(shè)置總數(shù)  
  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的時候執(zhí)行分頁查詢,pageSize<=0的時候不執(zhí)行相當(dāng)于可能只返回了一個count  
  58.             if (page.getPageSize() > 0 &&  
  59.                     ((rowBounds == RowBounds.DEFAULT && page.getPageNum() > 0)  
  60.                             || rowBounds != RowBounds.DEFAULT)) {  
  61.                 //將參數(shù)中的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.                 //執(zhí)行分頁查詢  
  67.                 Object result = invocation.proceed();  
  68.                 //得到處理結(jié)果  
  69.                 page.addAll((List) result);  
  70.             }  
  71.         } finally {  
  72.             ((PageSqlSource)ms.getSqlSource()).removeParser();  
  73.         }  
  74.         //返回結(jié)果  
  75.         return page;  
  76.     } 

源碼中注意關(guān)鍵的四點即可:

1、msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms)),創(chuàng)建count查詢的MappedStatement對象,并緩存于msCountMap。

2、如果count=true,則執(zhí)行count查詢,結(jié)果total值保存于page對象中,繼續(xù)執(zhí)行分頁查詢。

3、執(zhí)行分頁查詢,將查詢結(jié)果保存于page對象中,page是一個ArrayList對象。

4、args[2] = RowBounds.DEFAULT,改變Mybatis原有分頁行為;

args[1] = parser.setPageParameter(ms, args[1], boundSql, page),改變原有參數(shù)列表(增加分頁參數(shù))。

6. PageHelper的兩種使用方式

第一種、直接通過RowBounds參數(shù)完成分頁查詢 。 

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

第二種、PageHelper.startPage()靜態(tài)方法 

 
 
 
 
  1. //獲取第1頁,10條內(nèi)容,默認(rèn)查詢總數(shù)count  
  2.     PageHelper.startPage(1, 10);  
  3. //緊跟著的第一個select方法會被分頁  
  4.     List list = studentMapper.find();  
  5.     Page page = ((Page) list; 

注:返回結(jié)果list,已經(jīng)是Page對象,Page對象是一個ArrayList。

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

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

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


文章標(biāo)題:Mybatis:PageHelper分頁插件源碼及原理剖析
網(wǎng)頁網(wǎng)址:http://www.dlmjj.cn/article/cdsoghj.html