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

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

问题描述

首先是问题:我使用 XML 定义的查询,并且 SQL 包含数据库名称作为表名称的一部分.例如:SELECT * from 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天全站免登陆