SpringBoot_Mybatis_分頁

分頁分爲兩種:邏輯分頁和物理分頁。

邏輯分類就是:一次性從數據庫獲取所有數據,再通過後端的代碼獲取正確的分頁。

物理分頁就是:通過數據庫直接獲取分頁數據,例如編寫帶有limit的MySQL語句。

使用SpringBoot和Mybatis連接MySQL數據庫實現物理分頁,原理上都是基於limit關鍵字實現的。有以下三種方法:

1、在mapper.xml文件中直接編寫limit語句。limit n,m的意思是偏移量爲n,獲取m行數據。例如limit 5,10也就是獲取6-15行的數據。

2、編寫攔截器實現,解決不斷編寫limit語句的問題。原理就是,在mapper.xml中編寫普通的SQL語句,執行查詢之前,通過獲取方法參數,爲SQL語句加上limit關鍵詞。第三種方法的原理就是如此。

3、Mybatis分頁插件PageHelper。

下面是第3種的實現方法。

1、引入依賴。

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.13</version>
        </dependency>

2、兩句代碼解決。

            String orderBy = "info_id desc";//排序字段 空格 排序方式
            //設置分頁和排序
            PageHelper.startPage(1,10, orderBy);
            //獲取分頁數據
            List<InfosResponse> infoList = infoService.getInfoList(integer);
            //獲取分頁信息
            PageInfo<InfosResponse> pageInfo = new PageInfo<>(infoList);

大致原理如下:

package com.github.pagehelper;

@Intercepts({@Signature(
    type = Executor.class,
    method = "query",
    args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
), @Signature(
    type = Executor.class,
    method = "query",
    args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
)})
public class PageInterceptor implements Interceptor {
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] args = invocation.getArgs();
            MappedStatement ms = (MappedStatement)args[0];
            //mapper中方法傳入的參數,目前只有我們原始定義的
            Object parameter = args[1];
            RowBounds rowBounds = (RowBounds)args[2];
            ResultHandler resultHandler = (ResultHandler)args[3];
            //sql執行器
            Executor executor = (Executor)invocation.getTarget();
            CacheKey cacheKey;
            BoundSql boundSql;
            if (args.length == 4) {
                boundSql = ms.getBoundSql(parameter);
                cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            } else {
                cacheKey = (CacheKey)args[4];
                boundSql = (BoundSql)args[5];
            }

            this.checkDialectExists();
            List resultList;
            if (!this.dialect.skip(ms, parameter, rowBounds)) {
                if (this.dialect.beforeCount(ms, parameter, rowBounds)) {
                    //獲取總數據量
                    Long count = this.count(executor, ms, parameter, rowBounds, resultHandler, boundSql);
                    if (!this.dialect.afterCount(count, parameter, rowBounds)) {
                        Object var12 = this.dialect.afterPage(new ArrayList(), parameter, rowBounds);
                        return var12;
                    }
                }
                //執行sql語句,包括了插入limit
                resultList = ExecutorUtil.pageQuery(this.dialect, executor, ms, parameter, rowBounds, resultHandler, boundSql, cacheKey);
            } else {
                resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
            }

            Object var16 = this.dialect.afterPage(resultList, parameter, rowBounds);
            return var16;
        } finally {
            if (this.dialect != null) {
                this.dialect.afterAll();
            }

        }
    }
}
package com.github.pagehelper.util;
public abstract class ExecutorUtil {
    public static <E> List<E> pageQuery(Dialect dialect, Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql, CacheKey cacheKey) throws SQLException {
        if (!dialect.beforePage(ms, parameter, rowBounds)) {
            return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
        } else {
            //經過這一步之後,多了兩個傳入的參數First_PageHelper Second_PageHelper 對應的應該就是limit n,m中的n,m
            parameter = dialect.processParameterObject(ms, parameter, boundSql, cacheKey);
            //在原來的語句上多了limit ?
            String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, cacheKey);
            BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);
            Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
            Iterator var12 = additionalParameters.keySet().iterator();

            while(var12.hasNext()) {
                String key = (String)var12.next();
                pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
            }
            //交給mybatis執行語句了
            return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, pageBoundSql);
        }
    }

}

以上純屬個人理解的表層原理。

PageInterceptor 是一個Mybatis的攔截器,攔截了query的操作。對這些操作進行加工,也就是limit關鍵字的插入。這些加工操作發生在了ExecutorUtil 中。

關於使用PageHelper時,爲什麼要緊跟着查詢操作使用

先繼續看到ExecutorUtil 中:

     //經過這一步之後,多了兩個傳入的參數First_PageHelper Second_PageHelper 對應的應該就是limit n,m中的n,m
     parameter = dialect.processParameterObject(ms, parameter, boundSql, cacheKey);

 到PageHelper 中的:(這就和兩句代碼中的第一句對應上了,我們設置的分頁信息在這裏被獲取了)

package com.github.pagehelper;
public class PageHelper extends PageMethod implements Dialect {
    public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey) {
        return this.autoDialect.getDelegate().processParameterObject(ms, parameterObject, boundSql, pageKey);
    }
}
package com.github.pagehelper.dialect;    
public abstract class AbstractHelperDialect extends AbstractDialect implements Constant {
    public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey) {
        Page page = this.getLocalPage();
        ...
    }
}
package com.github.pagehelper.page;
public abstract class PageMethod {
    protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal();

    public static <T> Page<T> getLocalPage() {
        return (Page)LOCAL_PAGE.get();
    }
}

接下來套用官方的解釋:Mybatis-PageHelper

PageHelper 方法使用了靜態的 ThreadLocal 參數,分頁參數和線程是綁定的。

只要你可以保證在 PageHelper 方法調用後緊跟 MyBatis 查詢方法,這就是安全的。因爲 PageHelper 在 finally 代碼段中自動清除了 ThreadLocal 存儲的對象。

如果代碼在進入 Executor 前發生異常,就會導致線程不可用,這屬於人爲的 Bug(例如接口方法和 XML 中的不匹配,導致找不到 MappedStatement 時), 這種情況由於線程不可用,也不會導致 ThreadLocal 參數被錯誤的使用。

但是如果你寫出下面這樣的代碼,就是不安全的用法:

PageHelper.startPage(1, 10);
List<User> list;
if(param1 != null){
    list = userMapper.selectIf(param1);
} else {
    list = new ArrayList<User>();
}

這種情況下由於 param1 存在 null 的情況,就會導致 PageHelper 生產了一個分頁參數,但是沒有被消費,這個參數就會一直保留在這個線程上。當這個線程再次被使用時,就可能導致不該分頁的方法去消費這個分頁參數,這就產生了莫名其妙的分頁。

 

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