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
. Unfortunately, databases are created/named all over the place and
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:

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

But when I run the query
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?


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}