springboot中的mybatis是如果使用pagehelper的


springboot中使用其他組件都是基於自動配置的AutoConfiguration配置累的,pagehelper插件也是一樣的,通過PageHelperAutoConfiguration的,這個類存在於jar包的spring.factories

文件中,當springboot啟動時會通過selector自動將配置類加載到上下文中

springboot集成pagehelper,pom依賴:

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-autoconfigure</artifactId>   ---作用自動配置pagehelper
            <version>1.2.3</version>
        </dependency>

 

關鍵類:

PageHelperAutoConfiguration.java

package com.github.pagehelper.autoconfigure;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;

/**
 * 自定注入分頁插件
 *
 * @author liuzh
 */
@Configuration //表明當前了是一個配置類
@ConditionalOnBean(SqlSessionFactory.class)//當有SqlSesionFactory這個類的時候才實例化當前類
@EnableConfigurationProperties(PageHelperProperties.class)//pagehelpser的配置文件
@AutoConfigureAfter(MybatisAutoConfiguration.class)//當前類是在mybatisAutoconfiguration配置類初始化之后才初始化
public class PageHelperAutoConfiguration {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @Autowired
    private PageHelperProperties properties;//配置文件

    /**
     * 接受分頁插件額外的屬性
     *
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = PageHelperProperties.PAGEHELPER_PREFIX)//將配置文件實例化為properties
    public Properties pageHelperProperties() {
        return new Properties();
    }

    @PostConstruct//實例化之后條用當前方法,將pagehelper插件添加到myabtis的核心配置文件中(Configuration中) PageInterceptor就是pagehelper的插件
    public void addPageInterceptor() {
        PageInterceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        //先把一般方式配置的屬性放進去
        properties.putAll(pageHelperProperties());
        //在把特殊配置放進去,由於close-conn 利用上面方式時,屬性名就是 close-conn 而不是 closeConn,所以需要額外的一步
        properties.putAll(this.properties.getProperties());
        interceptor.setProperties(properties);
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
        }
    }

}

進一步看PageInterceptor.java,這個類就是mybatis的插件,先看類上的注解,@Interceptos注解表名當前類是一個攔截器,里邊會有@Signature注解,這個注解主要配置的就是攔截的方法,如type:攔截的類是Executor,method:攔截的方法,args:攔截方法

的參數

@Intercepts(//這個注解是mybatis中的注解
    {
        @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 {
    //緩存count查詢的ms
    protected Cache<String, MappedStatement> msCountMap = null;
    private Dialect dialect;//這個是pagehelper的一個接口,里邊有數據庫的一些方言配置
    private String default_dialect_class = "com.github.pagehelper.PageHelper";//默認的方言實現類,如果上邊那個dialect沒有配置的話,默認走這個
    private Field additionalParametersField;
    private String countSuffix = "_COUNT";

Dialect的一些實現類,不同的數據庫使用不同的實現類,其中,pagehelper是默認的方言(這個類是在沒有配置其他方言的時候,默認實例化的)

PageInterceptor類中的關鍵方法:intercept攔截方法,當攔截到相應的方法后,后走該改法判斷時候需要改變

@Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] args = invocation.getArgs();//獲取攔截到的方法的所有參數 下邊獲取0,1,2,3是進行強制轉換對應的類,這個是根據@intercepts注解中的@sisignature中的args得到的
            MappedStatement ms = (MappedStatement) args[0];
            Object parameter = args[1];
            RowBounds rowBounds = (RowBounds) args[2];
            ResultHandler resultHandler = (ResultHandler) args[3];
            Executor executor = (Executor) invocation.getTarget();
            CacheKey cacheKey;
            BoundSql boundSql;
            //由於邏輯關系,只會進入一次  分兩種情況4個參數和6個參數也是根據注解@signature的args類判斷的
            if(args.length == 4){
                //4 個參數時
                boundSql = ms.getBoundSql(parameter);
                cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            } else {
                //6 個參數時
                cacheKey = (CacheKey) args[4];
                boundSql = (BoundSql) args[5];
            }
            List resultList;
            //調用方法判斷是否需要進行分頁,如果不需要,直接返回結果  例如dialect使用的是默認的實現類的話,判斷是否要跳過分頁,是根據代碼中查詢數據庫是,是否執行過PageHelper.startPage()方法類判斷的(一種情況),執行過,則要分頁,否則不分頁
            if (!dialect.skip(ms, parameter, rowBounds)) {
                //反射獲取動態參數
                String msId = ms.getId();
                Configuration configuration = ms.getConfiguration();
                Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
          //下邊會進行兩步:1、總數查詢 2、分頁查詢
//判斷是否需要進行 count 查詢 if (dialect.beforeCount(ms, parameter, rowBounds)) { String countMsId = msId + countSuffix; Long count; //先判斷是否存在手寫的 count 查詢 MappedStatement countMs = getExistedMappedStatement(configuration, countMsId); if(countMs != null){ count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler); } else { countMs = msCountMap.get(countMsId); //自動創建 if (countMs == null) { //根據當前的 ms 創建一個返回值為 Long 類型的 ms countMs = MSUtils.newCountMappedStatement(ms, countMsId); msCountMap.put(countMsId, countMs); } count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler); } //處理查詢總數 //返回 true 時繼續分頁查詢,false 時直接返回 if (!dialect.afterCount(count, parameter, rowBounds)) { //當查詢總數為 0 時,直接返回空的結果 return dialect.afterPage(new ArrayList(), parameter, rowBounds); } } //判斷是否需要進行分頁查詢 if (dialect.beforePage(ms, parameter, rowBounds)) { //生成分頁的緩存 key CacheKey pageKey = cacheKey; //處理參數對象 parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey); //調用方言獲取分頁 sql String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey); BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter); //設置動態參數 for (String key : additionalParameters.keySet()) { pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); } //執行分頁查詢 resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql); } else { //不執行分頁的情況下,也不執行內存分頁 resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql); } } else { //rowBounds用參數值,不使用分頁插件處理時,仍然支持默認的內存分頁 resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); } return dialect.afterPage(resultList, parameter, rowBounds); } finally { dialect.afterAll(); } }

 

例子:

        Page<TUser> startPage = PageHelper.startPage(1, 2);
        List<TUser> list1 = mapper.selectByEmailAndSex1(params);

 //在查詢數據庫之前先執行startPage方法,傳入分頁參數進入starepage方法(這個方法在pagehelper的父類pagemethod中),startPage方法有多個重載的方法,該例子中用的是兩個參數的

 /**
     * 開始分頁
     *
     * @param pageNum  頁碼
     * @param pageSize 每頁顯示數量
     */
    public static <E> Page<E> startPage(int pageNum, int pageSize) {
        return startPage(pageNum, pageSize, true);
    }
   /**
     * 開始分頁
     *
     * @param pageNum  頁碼
     * @param pageSize 每頁顯示數量
     * @param count    是否進行count查詢
     */
    public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count) {
        return startPage(pageNum, pageSize, count, null, null);
    }
   /**
     * 開始分頁
     *
     * @param pageNum      頁碼
     * @param pageSize     每頁顯示數量
     * @param count        是否進行count查詢
     * @param reasonable   分頁合理化,null時用默認配置
     * @param pageSizeZero true且pageSize=0時返回全部結果,false時分頁,null時用默認配置
     */
    public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
        Page<E> page = new Page<E>(pageNum, pageSize, count);
        page.setReasonable(reasonable);
        page.setPageSizeZero(pageSizeZero);
        //當已經執行過orderBy的時候
        Page<E> oldPage = getLocalPage();//查詢ThreadLocal中是否已經有了page
        if (oldPage != null && oldPage.isOrderByOnly()) {
            page.setOrderBy(oldPage.getOrderBy());
        }
        setLocalPage(page);
        return page;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM