1

我正在尝试基于来自 mybatis 配置的参数而不是查询参数来创建条件查询片段。像这样的东西:

<sql id="frag">
    <if test="col_name != null">
        SELECT * FROM TABLE WHERE ${col.name}=#{value}
    </if>
    <if test="col_name == null">
        SELECT * FROM TABLE WHERE SAMPLECOL=#{value}
    </if>
</sql>

其中的值col_name是一个全局参数,在 mybatis 配置读取的 .properties 文件中指定。

显然这不起作用;${...}查看源代码,OGNL 表达式评估器似乎不知道配置属性(当我通过SQL进行参数替换时,这些属性正在工作)。有没有人找到办法做到这一点?

4

1 回答 1

1

我发现这是目前不可能的;OGNL 实际上无法访问配置属性。

作为一种解决方法,正如mybatis 邮件列表上的这篇文章中所建议的那样,我编写了一个简单的拦截器,它读取配置参数并将它们添加到查询参数映射中。不完全干净,但它有效。

拦截器代码:

@Intercepts({
    @Signature(type = Executor.class,
    method = "query",
    args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class ConfigPropInterceptor implements Interceptor {

    private final Map<String, Object> properties = new HashMap<String, Object>();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object param = invocation.getArgs()[1];
        if (param instanceof Map) {
            ((Map<String, Object>)param).putAll(properties);
        }
        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties) {
        for (String p : properties.stringPropertyNames()) {
            this.properties.put(p, properties.getProperty(p));
        }
    }
}

配置 .xml 中的示例用法:

<plugins>
    <plugin interceptor="...ConfigPropInterceptor">
        <property name="_issuerLocation" value="${issuer.location}"/>
    </plugin>
</plugins>

使用此设置,我能够_issuerLocation像其他所有内容一样测试 OGNL 表达式中的变量。

于 2012-08-16T12:26:40.650 回答