Mybatis 攔截器實(shí)現(xiàn) Like 通配符轉(zhuǎn)義

緣起

在 Mybatis 執(zhí)行 like 查詢時(shí),如果查詢字符包含通配符‘%’或‘_’則查詢結(jié)果并不是我們預(yù)期結(jié)果。比如,一張文件表里有字段 file_name 記錄文件名,而我們需要找到以‘_’開頭的文件琅捏。查詢語(yǔ)句是這樣: select * from file where file_name like '_%' 。如果你了解mysql 就知道執(zhí)行該語(yǔ)句將返回表中所有的文件名不為空的記錄递雀。這實(shí)際是與我們目標(biāo)相悖柄延。正確的語(yǔ)句應(yīng)該是 select * from file where file_name like "\\_%"(默認(rèn)轉(zhuǎn)義字符是反斜杠)。

代碼

不止一次遇到該問題了,之前的解決辦法搜吧,是在 mapper 的參數(shù)中做轉(zhuǎn)義市俊。比如下面這段代碼(是一個(gè)帖子搜索參數(shù)的定義,我們重點(diǎn)關(guān)注 titlePrefix 這代表標(biāo)題是一個(gè)前綴匹配)


@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PostSearchParam implements Serializable {

    private Integer type;
    /**
     * 標(biāo)題前綴
     */
    private String titlePrefix;
    /**
     * 學(xué)院名稱
     */
    private String groupName;
    /**
     * userId
     */
    private Integer userId;
}

為了實(shí)現(xiàn)轉(zhuǎn)義滤奈,添加一個(gè)新的getter方法來(lái)獲取轉(zhuǎn)義后的標(biāo)題

....
public String getEscapeTitlePrefix(){
    return likeEscape(this.titlePrefix);
}

String escapeLike(String value) {
        if (value != null) {
            return value
                .replaceAll("_", "\\\\_")
                .replaceAll("%", "\\\\%");
        }
        return null;
    }
...

雖然能夠?qū)崿F(xiàn)預(yù)期摆昧,但是你想想,如果有很多這樣的類蜒程,那我們需要敲很多遍一樣的代碼绅你。為了“永絕后患”,可以通過mybatis攔截器去除冗余代碼昭躺。

攔截器的主要內(nèi)容:1. 識(shí)別 mapper 中的sql語(yǔ)句中包含like查詢(正則)忌锯;2. 找到like后的占位符,將該占位的字符串轉(zhuǎn)義领炫。

/**
 * Like 轉(zhuǎn)義
 * <p>
 * 使用方法:
 * <ol>
 * <li> 添加插件 </li>
 * </ol>
 * </p>
 */
@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 LikeStringEscapeInterceptor implements Interceptor {

    /**
     * 檢查sql中偶垮,是否含有l(wèi)ike查詢
     */
    private static Pattern LIKE_PARAM_PATTERN = Pattern
            .compile("like\\s+['\"%_]*\\?", Pattern.CASE_INSENSITIVE);

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

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        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();
        CacheKey cacheKey;
        BoundSql boundSql;
        //由于邏輯關(guān)系,只會(huì)進(jìn)入一次
        if (args.length == 4) {
            //4 個(gè)參數(shù)時(shí)
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            //6 個(gè)參數(shù)時(shí)
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }

        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        StatementType statementType = ms.getStatementType();
        // 只處理 有參數(shù)的查詢語(yǔ)句
        if (sqlCommandType == SqlCommandType.SELECT
                && statementType == StatementType.PREPARED) {
            escapeParameterIfContainingLike(boundSql);
            return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
        }
        return invocation.proceed();
    }

    void escapeParameterIfContainingLike(BoundSql boundSql) {
        if (boundSql == null) {
            return;
        }
        String prepareSql = boundSql.getSql();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

        // 找到 like 后面的參數(shù)
        List<Integer> position = findLikeParam(prepareSql);
        if (position == null || position.size() == 0) {
            return;
        }

        List<ParameterMapping> likeParameterMappings = new ArrayList<>();

       // 復(fù)制
        MetaObject metaObject = MetaObjectUtil.forObject(boundSql.getParameterObject());
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping pm = parameterMappings.get(i);
            String property = pm.getProperty();
            // 忽略無(wú)法處理的屬性帝洪。例如 __frch_
            if (metaObject.hasGetter(property)) {
                boundSql.setAdditionalParameter(property, metaObject.getValue(property));
                if (position.contains(i)) {
                    likeParameterMappings.add(pm);
                }
            }
        }

        // 覆蓋 轉(zhuǎn)義字符
        delegateMetaParameterForEscape(boundSql, likeParameterMappings);
    }


    /**
     * @param boundSql              原 boundSql
     * @param likeParameterMappings 需要轉(zhuǎn)義的參數(shù)
     * @return 支持轉(zhuǎn)義的 boundSql
     */
    void delegateMetaParameterForEscape(BoundSql boundSql, List<ParameterMapping> likeParameterMappings) {

        for (ParameterMapping mapping : likeParameterMappings) {
            String property = mapping.getProperty();

            MetaObject metaObject = MetaObjectUtil.forObject(boundSql.getParameterObject());
            Object value = metaObject.getValue(property);
            if (value instanceof String) {
                boundSql.setAdditionalParameter(property, escapeLike((String) value));
            }
        }
    }

    String escapeLike(String value) {
        if (value != null) {
            return value
                    .replaceAll("_", "\\\\_")
                    .replaceAll("%", "\\\\%");
        }
        return null;
    }


    List<Integer> findLikeParam(String prepareSql) {
        Matcher matcher = LIKE_PARAM_PATTERN.matcher(prepareSql);

        int pos = 0;
        List<Integer> indexes = new ArrayList<>();

        while (matcher.find(pos)) {
            int start = matcher.start();
            int index = StringUtils.countMatches(prepareSql.substring(0, start), "?");
            indexes.add(index);
            pos = matcher.end();
        }
        return indexes;
    }
}

使用

如果需要使用似舵,請(qǐng)?zhí)砑拥?code>mybatis的插件中

<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
    <plugin
      interceptor="xxxxx.LikeStringEscapeInterceptor"/>
  </plugins>

如有錯(cuò)誤,歡迎大家指正葱峡。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末啄枕,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子族沃,更是在濱河造成了極大的恐慌,老刑警劉巖泌参,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件脆淹,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡沽一,警方通過查閱死者的電腦和手機(jī)盖溺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)铣缠,“玉大人烘嘱,你說(shuō)我怎么就攤上這事』韧埽” “怎么了蝇庭?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)捡硅。 經(jīng)常有香客問我哮内,道長(zhǎng),這世上最難降的妖魔是什么壮韭? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任北发,我火速辦了婚禮纹因,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘琳拨。我一直安慰自己瞭恰,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布狱庇。 她就那樣靜靜地躺著惊畏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪僵井。 梳的紋絲不亂的頭發(fā)上陕截,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音批什,去河邊找鬼农曲。 笑死,一個(gè)胖子當(dāng)著我的面吹牛驻债,可吹牛的內(nèi)容都是我干的乳规。 我是一名探鬼主播,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼合呐,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼暮的!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起淌实,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤冻辩,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后拆祈,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體恨闪,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年放坏,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了咙咽。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡淤年,死狀恐怖钧敞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情麸粮,我是刑警寧澤溉苛,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站弄诲,受9級(jí)特大地震影響炊昆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一凤巨、第九天 我趴在偏房一處隱蔽的房頂上張望视乐。 院中可真熱鬧,春花似錦敢茁、人聲如沸佑淀。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)伸刃。三九已至,卻和暖如春逢倍,著一層夾襖步出監(jiān)牢的瞬間捧颅,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工较雕, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留碉哑,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓亮蒋,卻偏偏與公主長(zhǎng)得像扣典,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子慎玖,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

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