MyBatis - global parameter definition

First problem: I use XML-specific queries, and SQL contains the database name as part of the table name. For example: SELECT * from mydb.bar . Unfortunately, databases are created / called everywhere, and the mudb part mudb really dynamic and can change at any time. So I wanted to replace it with a property so that it looked 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} , it is null. The same thing happens if I define this property in the properties file. I would really like to pass this as part of the parameters of each call, since this is a truly global property. It can be done? And if so, how?

+6
source share
3 answers

Yes, you can! Perhaps this is a rather strange undocumented feature. When creating the Configuration object, do something similar. (Org.apache.ibatis.session.Configuration)

 configuration.getVariables().put("global_param", "123"); 

Then you can link to your XML map.

  select * from ${global_param} 
+4
source

I had the same problem using Spring + MyBatis and solved it by setting "configurationProperties" using Spring XML definition for sqlSessionFactory. The following example shows how to set a custom global property called "encryptionKey" with a value that you can either hardcode in an XML file or load from an external file using the context-placeholder tag of the context: (as shown below).

 <context:property-placeholder location="/WEB-INF/spring/config-datasource.properties" /> <beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="typeAliasesPackage" value="com.example.model" /> <beans:property name="configurationProperties"> <beans:props> <beans:prop key="encryptionKey">${jdbc.encryptionKey}</beans:prop> </beans:props> </beans:property> </beans:bean> 
+3
source

I used XML configuration, but not Spring, and set the property inside the Configuration object, but found that it had to be done before the map files were loaded (see here ). I abandoned the “Configuration Object” object and went with the approach that worked for me:

  Reader reader = Resources.getResourceAsReader("..../mybatis-config.xml"); Properties properties = new Properties(); properties.setProperty("dbname", "mydb"); SqlSessionFactory.factory = new SqlSessionFactoryBuilder().build(reader, "development", properties); 

Then, as Andy Pryor wrote, use select * from ${dbname} in the XML converter.

0
source

Source: https://habr.com/ru/post/903146/


All Articles