MyBatis - defining a global parameter

Bostone picture Bostone · Dec 5, 2011 · Viewed 8.5k times · Source

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?

Answer

Andy picture Andy · Dec 7, 2011

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");

Then in your XML map, you can reference.

    select * from ${global_param}