05 mybatis攔截器

說明

之前使用了com.github.pagehelper.pagehelper實現(xiàn)分頁锻梳,現(xiàn)在參考源代碼,自己簡單實現(xiàn)一下功能邦鲫。
插件源碼地址:https://github.com/pagehelper/Mybatis-PageHelper

基礎(chǔ)代碼

基礎(chǔ)代碼可以參考:《SpringBoot項目實戰(zhàn)(001)mybatis通過xml實現(xiàn)mapper》

主要代碼說明

  • DataSourceConfig:數(shù)據(jù)源配置,可以配置mybatis的攔截器
  • PageInfo古今;用于傳入分頁參數(shù)
  • Dialect滔以;方言,針對不同數(shù)據(jù)庫抵碟,實現(xiàn)不同的方言坏匪,本文使用mysql
  • MybatisInterceptor适滓;mybatis攔截器,實現(xiàn)分頁功能

第一步罚屋,安裝攔截器

首先把攔截器創(chuàng)建出來嗅绸,并在mybatis的config中,使用攔截器猛拴。

簡單修改DataSourceConfig.java

    // mybatis配置
    private org.apache.ibatis.session.Configuration createMybatisConfig() {
        ......
        // 加入攔截器
        config.addInterceptor(getMybatisIntercepts());
        return config;
    }
    private Interceptor getMybatisIntercepts() {
        Interceptor interceptor = new MybatisInterceptor();
        return interceptor;
    }

MybatisInterceptor.java代碼瞧柔,基本上是空的

package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * MybatisInterceptor
 */
@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 MybatisInterceptor implements Interceptor {
    private volatile IDialect dialect;

    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] args = invocation.getArgs();
            return null;
        } finally {
            if (dialect != null) {
                dialect.afterAll();
            }
        }
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
}

IDialect.java

package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.RowBounds;
public interface IDialect {
    void afterAll();
    String getPagedSql(BoundSql boundSql,RowBounds rowBounds);
}

斷點打在MybatisInterceptorintercept方法處,運行debug哥蔚,postman調(diào)個GET方法蛛蒙,可得:

在這里插入圖片描述

可以看到,有四個參數(shù)深夯,仔細看一下,大致功能:

  1. mybatis的mapper方面的信息
  2. 參數(shù)方面的信息
  3. 分頁信息:limit offset
  4. null

那我們需要做的就是找到查詢語句雹拄,根據(jù)dialect改寫為分頁的語句掌呜,返回結(jié)果即可滓玖。

第二步质蕉,調(diào)整功能

整理參數(shù)模暗,把三個參數(shù)包括Executor都整理出來。我們的目的是通過調(diào)整sql語句绷蹲,再使用Executor完成原本的調(diào)用顾孽。

        // 參數(shù)
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        // 執(zhí)行器
        Executor executor = (Executor) invocation.getTarget();
        // sql
        BoundSql boundSql = ms.getBoundSql(parameter);
        // 分頁sql
        String sql = dialect.getPagedSql(boundSql, rb);

新增MySqlDialect若厚,實現(xiàn)功能getPageSql,將BoundSql中的sql調(diào)整為分頁的疤估。

//實現(xiàn)
package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

public class MySqlDialect implements IDialect {
    @Override
    public void afterAll() {
    }

    @Override
    public String getPagedSql(BoundSql boundSql, RowBounds rowBounds) {
        String sql = boundSql.getSql();
        StringBuilder sb = new StringBuilder();
        sb.append(sql);
        sb.append(" LIMIT ");
        sb.append(rowBounds.getOffset());
        sb.append(",");
        sb.append(rowBounds.getLimit());
        return sb.toString();
    }
}

第三步霎冯,輸入?yún)?shù)

現(xiàn)在修改整條request鏈路沈撞,所有findall方法增加pageinfo參數(shù)。

首先缠俺,新增pageinfo類型:

package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import lombok.Data;

@Data
public class PageInfo  {
    // 分頁壹士,第幾頁
    private int pageNum;
    // 分頁,每頁大小
    private int pageSize;
}

OrderController 修改 orders 方法唯笙,增加一個參數(shù)

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<OrderBean> orders(OrderCondition orderCondition,PageInfo pageinfo) {
        return orderService.findAll(orderCondition,pageinfo);
    }

IBaseService 修改findall方法,增加pageinfo參數(shù)七嫌,注意@Param("pageinfo")定義參數(shù)的名字

    default List<Bean> findAll(@Param("conditionQC") Condition condition,@Param("pageinfo") PageInfo
     pageinfo){
        return getBaseDao().findAll(condition,pageinfo);
    }

IBaseDao 修改findall方法抄瑟,增加pageinfo參數(shù)枉疼,注意@Param("pageinfo")定義參數(shù)的名字

    public List<Bean> findAll(@Param("conditionQC") Condition conditionQC,@Param("pageinfo") PageInfo pageinfo);

第四步,完善攔截器

在攔截器中找到pageinfo參數(shù)惹资,如果有分頁參數(shù)航闺,就將值傳給方言進行分頁,最后返回數(shù)據(jù)侮措。
方言可以通過datasource的配置乖杠,自動讀取,本文直接設(shè)置為MysqlDialect畏吓。

    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] args = invocation.getArgs();
            MappedStatement ms = (MappedStatement) args[0];
            Object parameter = args[1];
            RowBounds rowBounds = (RowBounds) args[2];
            ResultHandler resultHandler = (ResultHandler) args[3];
            Executor executor = (Executor) invocation.getTarget();
            BoundSql boundSql = ms.getBoundSql(parameter);

            ParamMap params = (ParamMap) parameter;
            // 判斷參數(shù)中是否有分頁
            if (params.containsKey("pageinfo")) {
                PageInfo pageinfo = (PageInfo) params.get("pageinfo");
                if (pageinfo.getPageNum() > 0 && pageinfo.getPageSize() > 0) {
                    RowBounds rb = new RowBounds((pageinfo.getPageNum() - 1) * pageinfo.getPageSize(),
                            pageinfo.getPageSize());
                    // 使用方言分頁
                    String sql = dialect.getPagedSql(boundSql, rb);
                    boundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), parameter);
                    return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, null, boundSql);
                }
            }
            return invocation.proceed();
        } finally {
            if (dialect != null) {
                dialect.afterAll();
            }
        }
    }

使用postman測試

list方法菲饼,使用分頁參數(shù)列赎,返回分頁結(jié)果:

list方法粥谬,使用分頁參數(shù)

list方法,不使用分頁參數(shù),返回所有結(jié)果:

list方法掺喻,不使用分頁參數(shù)

findOne方法(后臺不接受分頁參數(shù)),可以看到加入分頁參數(shù)褂乍,也不會分頁:

findOne方法(后臺不接受分頁參數(shù))逃片,可以看到加入分頁參數(shù)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末只酥,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子损离,更是在濱河造成了極大的恐慌绝编,老刑警劉巖十饥,帶你破解...
    沈念sama閱讀 222,729評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逗堵,死亡現(xiàn)場離奇詭異,居然都是意外死亡砸捏,警方通過查閱死者的電腦和手機垦藏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來轰驳,“玉大人弟灼,你說我怎么就攤上這事田绑。” “怎么了掩驱?”我有些...
    開封第一講書人閱讀 169,461評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長丁寄。 經(jīng)常有香客問我系吩,道長,這世上最難降的妖魔是什么吆你? 我笑而不...
    開封第一講書人閱讀 60,135評論 1 300
  • 正文 為了忘掉前任早处,我火速辦了婚禮瘫析,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘贬循。我一直安慰自己,他們只是感情好烂瘫,可當(dāng)我...
    茶點故事閱讀 69,130評論 6 398
  • 文/花漫 我一把揭開白布坟比。 她就那樣靜靜地躺著嚷往,像睡著了一般。 火紅的嫁衣襯著肌膚如雪籍琳。 梳的紋絲不亂的頭發(fā)上贷祈,一...
    開封第一講書人閱讀 52,736評論 1 312
  • 那天势誊,我揣著相機與錄音,去河邊找鬼闻丑。 笑死勋颖,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的侥祭。 我是一名探鬼主播茄厘,決...
    沈念sama閱讀 41,179評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼次哈,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了琼牧?” 一聲冷哼從身側(cè)響起哀卫,我...
    開封第一講書人閱讀 40,124評論 0 277
  • 序言:老撾萬榮一對情侶失蹤此改,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后共啃,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,657評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡移剪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,723評論 3 342
  • 正文 我和宋清朗相戀三年究珊,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片挂滓。...
    茶點故事閱讀 40,872評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡苦银,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出赶站,到底是詐尸還是另有隱情幔虏,我是刑警寧澤,帶...
    沈念sama閱讀 36,533評論 5 351
  • 正文 年R本政府宣布贝椿,位于F島的核電站想括,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏瑟蜈。R本人自食惡果不足惜烟逊,卻給世界環(huán)境...
    茶點故事閱讀 42,213評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望铺根。 院中可真熱鬧宪躯,春花似錦、人聲如沸位迂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽掂林。三九已至臣缀,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間泻帮,已是汗流浹背精置。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留锣杂,地道東北人脂倦。 一個月前我還...
    沈念sama閱讀 49,304評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像蹲堂,于是被迫代替她去往敵國和親狼讨。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,876評論 2 361

推薦閱讀更多精彩內(nèi)容