MyBatis - 定义全局参数
首先是问题:我使用 XML 定义的查询,并且 SQL 包含数据库名称作为表名称的一部分。例如:从 mydb.bar 中选择 *
。不幸的是,数据库是在各处创建/命名的,而 mudb 部分实际上是动态的,可以随时更改。所以我想用一个属性替换它,这样它看起来像 SELECT * FROM ${dbname}.bar 然后我在 mybatis-config.xml 中定义了以下部分:
<properties>
<property name="dbname" value="mydb"/>
</properties>
但是当我运行查询时${dbname}
计算结果为 null。如果我在属性文件中定义此属性,也会发生同样的情况。我不想将其作为每个调用参数的一部分传递,因为这确实是一个全局属性。这可以做到吗?如果是的话——怎么办?
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>
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你可以!这可能是一个奇怪的未记录的功能。构建配置对象时,请执行以下操作。 (org.apache.ibatis.session.Configuration)
然后在你的XML映射中,你可以引用。
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)
Then in your XML map, you can reference.
我在使用 Spring+MyBatis 时遇到了同样的问题,并通过使用我的 sqlSessionFactory 的 Spring XML 定义设置“configurationProperties”来解决它。下面的示例展示了如何设置名为“encryptionKey”的自定义全局属性,您可以在 XML 文件中硬编码该值,也可以使用 context:property-placeholder 标记从外部文件加载该值(如下所示)。
I had the same issue using Spring+MyBatis, and solved it by setting 'configurationProperties' using my Spring XML definition for sqlSessionFactory. My example below shows how to set a custom global property named 'encryptionKey', with a value which you can either hard-code in the XML file, or load from an external file using the context:property-placeholder tag (as below).
我使用的是 XML 配置,而不是 Spring,并在 Configuration 对象内设置了一个属性,但发现必须在加载映射器文件之前完成(请参阅 此处)。我放弃了配置对象方法并采用了这种对我有用的方法:
然后,正如 Andy Pryor 发布的那样,在 XML 映射器中使用
select * from ${dbname}
。I was using an XML configuration but not Spring and set a property inside the Configuration object but discovered that had to be done before the mapper files are loaded (see here). I abandoned the Configuration object approach and went with this approach, which worked for me:
Then, as Andy Pryor posted, use
select * from ${dbname}
in the XML mapper.