我正在为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.....) {
}
有一种方法可以通过修改用于创建查询条件的'Example'类来实现。假设您有一个名为Label
的Mybatis域对象。这将具有关联的LabelExample
。注意,我已经将'binary'限定词添加到了生成的标准方法中。这似乎为我完成了工作,并导致区分大小写的查询。
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 doc中定义为这种形式:
TestTableExample example = new TestTableExample();
example.createCriteria().andField1EqualTo("abc");
这将导致这样的查询过滤器:
where field1 = 'abc'
相反,我认为您需要使用复杂查询形式,并将其与plugin组合以启用ILIKE式搜索。
[
/*
* 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;
}
}
实现起来似乎有点痛苦,而且不幸的是,就像高级功能经常出现的情况一样,唯一的文档实际上是已登录到[[git存储库中的示例。您可能希望使用Mybatis中内置的SQL Builder类,在这里您可以使用Mybatis
WHERE
方法并在参数中指定ILIKE
,尽管我知道这也可能是桥梁远未给出generator
代码的当前用法。您可以使用不敏感的字符,例如'XXXX',它可以与任何数据库一起使用