Bostone Bostone - 7 months ago 18
Java Question

MyBatis - defining a global parameter

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

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}