簡體   English   中英

如何強制 Mybatis 使用動態條件進行區分大小寫的選擇

[英]How to force Mybatis to do a case sensitive select using dynamic criteria

我正在為 Mybatis DB 映射器構建動態查詢,以訪問 MySql 數據庫。 查詢由包含選擇字段的 XML 配置文件驅動。 所以我動態創建了一個 critera 對象。 我的問題是,如果選擇字段之一是字符串,則選擇返回不需要的記錄,因為它不區分大小寫

例如,如果選擇值為“Analog1”,這將匹配值為“analog1”的記錄。

問題是,我可以強制底層 SELECT 區分大小寫嗎? 我知道

select * from Label where binary Label_Name = 'analog1';

只會匹配 'analog1' 而不是 'Analog1'。 但是如何告訴 Mybatis 查詢在查詢中使用二進制限定符呢?

這是我創建條件的代碼。 如您所見,這一切都是使用反射動態完成的,沒有任何硬編碼:

private Object findMatchingRecord(TLVMessageHandlerData data, Object databaseMapperObject, Object domainObject, ActiveRecordDataType activeRecordData)
        throws TLVMessageHandlerException {

    if (activeRecordData == null) {
        return false;
    }

    String domainClassName = domainObject.getClass().getName();

    try {
        String exampleClassName = domainClassName + "Example";
        Class<?> exampleClass = Class.forName(exampleClassName);
        Object exampleObject = exampleClass.newInstance();
        Method createCriteriaMethod = exampleClass.getDeclaredMethod("createCriteria", (Class<?>[])null);
        Object criteriaObject = createCriteriaMethod.invoke(exampleObject, (Object[])null);

        for (String selectField : activeRecordData.getSelectField()) {
            String criteriaMethodName = "and" + firstCharToUpper(selectField) + "EqualTo";
            Class<?> selectFieldType = domainObject.getClass().getDeclaredField(selectField).getType();
            Method criteriaMethod = criteriaObject.getClass().getMethod(criteriaMethodName, selectFieldType);
            Method getSelectFieldMethod = domainObject.getClass().getDeclaredMethod("get" + firstCharToUpper(selectField));
            Object selectFieldValue = getSelectFieldMethod.invoke(domainObject, (Object[])null);
            if (selectFieldValue != null) {
                criteriaMethod.invoke(criteriaObject, new Object[] { selectFieldValue });
            }
        }

        List<?> resultSet = tlvMessageProcessingDelegate.selectByExample(databaseMapperObject, exampleObject);

        if (resultSet.size() > 0) {
            return resultSet.get(0);
        }
        else {
            return null;
        }

    } 
    catch(..... Various exceptions.....) {
    }

有一種方法可以通過修改用於創建查詢條件的“示例”類來做到這一點。 假設您有一個名為Label的 Mybatis 域對象。 這將有一個關聯的LabelExample 請注意,我已將“二進制”限定符添加到生成的標准方法中。 這似乎為我完成了這項工作,並導致區分大小寫的查詢。

public class LabelExample {

...

/**
 * This class was generated by MyBatis Generator. This class corresponds to the database table Label
 * @mbggenerated
 */
    protected abstract static class GeneratedCriteria {

        public Criteria andLabelNameEqualTo(String value) {
            addCriterion("binary Label_Name =", value, "labelName");
            return (Criteria) this;
        }
    ...
}

我相信這是可能的,但不能使用簡單的查詢樣式。

這在Mybatis Generator 文檔中定義為以下形式:

TestTableExample example = new TestTableExample();
example.createCriteria().andField1EqualTo("abc");

這會導致這樣的查詢過濾器:

where field1 = 'abc'

相反,我認為您需要使用復雜的查詢表單並將其與插件結合以啟用ILIKE -esque 搜索。

有一個這樣的插件示例,它隨mybatis-generator 一起提供 為了完整起見,我重現了下面的代碼:

/*
 *  Copyright 2009 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.mybatis.generator.plugins;

import java.util.List;

import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.codegen.ibatis2.Ibatis2FormattingUtilities;

/**
 * This plugin demonstrates adding methods to the example class to enable
 * case-insensitive LIKE searches. It shows hows to construct new methods and
 * add them to an existing class.
 * 
 * This plugin only adds methods for String fields mapped to a JDBC character
 * type (CHAR, VARCHAR, etc.)
 * 
 * @author Jeff Butler
 * 
 */
public class CaseInsensitiveLikePlugin extends PluginAdapter {

    /**
     * 
     */
    public CaseInsensitiveLikePlugin() {
        super();
    }

    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
            IntrospectedTable introspectedTable) {

        InnerClass criteria = null;
        // first, find the Criteria inner class
        for (InnerClass innerClass : topLevelClass.getInnerClasses()) {
            if ("GeneratedCriteria".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$
                criteria = innerClass;
                break;
            }
        }

        if (criteria == null) {
            // can't find the inner class for some reason, bail out.
            return true;
        }

        for (IntrospectedColumn introspectedColumn : introspectedTable
                .getNonBLOBColumns()) {
            if (!introspectedColumn.isJdbcCharacterColumn()
                    || !introspectedColumn.isStringColumn()) {
                continue;
            }

            Method method = new Method();
            method.setVisibility(JavaVisibility.PUBLIC);
            method.addParameter(new Parameter(introspectedColumn
                    .getFullyQualifiedJavaType(), "value")); //$NON-NLS-1$

            StringBuilder sb = new StringBuilder();
            sb.append(introspectedColumn.getJavaProperty());
            sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
            sb.insert(0, "and"); //$NON-NLS-1$
            sb.append("LikeInsensitive"); //$NON-NLS-1$
            method.setName(sb.toString());
            method.setReturnType(FullyQualifiedJavaType.getCriteriaInstance());

            sb.setLength(0);
            sb.append("addCriterion(\"upper("); //$NON-NLS-1$
            sb.append(Ibatis2FormattingUtilities
                    .getAliasedActualColumnName(introspectedColumn));
            sb.append(") like\", value.toUpperCase(), \""); //$NON-NLS-1$
            sb.append(introspectedColumn.getJavaProperty());
            sb.append("\");"); //$NON-NLS-1$
            method.addBodyLine(sb.toString());
            method.addBodyLine("return (Criteria) this;"); //$NON-NLS-1$

            criteria.addMethod(method);
        }

        return true;
    }
}

實現起來似乎有點痛苦,不幸的是,高級Mybatis功能似乎經常出現這種情況,唯一的文檔實際上是檢入git repo 的示例。

您可能想看看使用內置於MybatisSQL Builder類,您可以在其中使用WHERE方法並在參數中指定ILIKE ,盡管我知道考慮到生成器代碼的當前使用情況,這可能是一個橋梁。

有一個 mybatis 生成器插件org.mybatis.generator.plugins.CaseInsensitiveLikePlugin

該插件向 Example 類(實際上是 Criteria 內部類)添加方法以支持不區分大小寫的 LIKE 搜索

您可以使用不敏感的“XXXX”,它可以與任何數據庫一起使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM