如何强制Mybatis使用动态条件进行区分大小写选择

时间:2014-07-25 12:31:02

标签: java mysql mybatis

我正在为Mybatis DB映射器构建动态查询,以访问MySql数据库。查询由包含选择字段的XML配置文件驱动。所以我动态创建一个critera对象。 我的问题是,如果其中一个选择字段是一个字符串,那么select会返回不需要的记录,因为它不区分大小写

例如,如果选择值为“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.....) {
    }

3 个答案:

答案 0 :(得分:0)

我相信它可以做,但不能使用简单查询样式。

Mybatis Generator doc中定义的内容为:

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

这会导致像这样的查询过滤器:

where field1 = 'abc'

相反,我认为您需要使用复杂查询表单并将其与插件结合使用以启用 ILIKE -esque搜索。< / p>

mybatis-generator 附带了example这样的插件。我重现下面的代码是为了完整性:

/*
 *  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 回购。

您可能希望使用内置于 Mybatis SQL Builder类,您可以使用WHERE方法并在参数中指定ILIKE ,虽然我知道,鉴于当前使用 generator 代码,这可能是一个太过分的桥梁。

答案 1 :(得分:0)

有一种方法可以通过修改&#39;示例&#39;用于创建查询条件的类。 假设您有一个名为Label的Mybatis域对象。这将有一个关联的LabelExample。请注意我已经添加了二进制文件&#39;生成标准方法的限定符。这似乎对我有用,并导致区分大小写的查询。

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;
        }
    ...
}

答案 2 :(得分:0)

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

此插件将方法添加到Example类(实际上是Criteria内部类),以支持不区分大小写的LIKE搜索

您可以使用“ XXXX”之类的不敏感内容,它可以与任何数据库一起使用