MyBatis - 定义全局参数 [英] MyBatis - defining a global parameter

查看:250
本文介绍了MyBatis - 定义全局参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先是问题:我使用XML定义的查询,SQL包含数据库名称作为表名的一部分。例如: SELECT *来自mydb.bar 。不幸的是,数据库是在所有地方创建/命名的, mudb 部分非常动态,可以随时更改。所以我想用属性替换它,所以它看起来像 SELECT * FROM $ {dbname} .bar 然后我在mybatis-config.xml中定义了以下部分:

First the problem: I'm using XML-defined queries and the SQL contains database name as part of a table name. For example: SELECT * from mydb.bar. Unfortunately, databases are created/named all over the place and mudb part is really dynamic and can change at any moment. So I wanted to replace it with a property so it would look like SELECT * FROM ${dbname}.bar and then I defined the following section in mybatis-config.xml:

<properties>
    <property name="dbname" value="mydb"/>
</properties>

但是当我运行查询 $ {dbname} 计算为null。如果我在属性文件中定义此属性,也会发生相同的情况我不想将此作为每个调用参数的一部分传递,因为这是一个真正的全局属性。可以这样做吗?如果是 - 怎么样?

But when I run the query ${dbname} evaluates to null. Same happens if I define this property in the properties file. I would hate to pass this as part of the each call parameters since this is truly a global property. Can this be done? And if yes - how?

推荐答案

是的,你可以!这可能是一种奇怪的无证特征。构建Configuration对象时,请执行以下操作。 (org.apache.ibatis.session.Configuration)

Yes, you can! This is kind of a weird undocumented feature maybe. When building your Configuration object, do something like this. (org.apache.ibatis.session.Configuration)

configuration.getVariables().put("global_param", "123");

然后在您的XML地图中,您可以参考。

Then in your XML map, you can reference.

    select * from ${global_param}

这篇关于MyBatis - 定义全局参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆