Scope variables in spring/mybatis maps
Question
I have a conversationScope.myVar="myValue" variable;
I would like to use it inside a mybatis map such as,
select col1, col1, conversationScope.myVar as ScopeVar
from table1;
desired result
col1 col2 ScopeVar
xxxx xxxx myValue
yyyy yyyy myValue
...
Solution
MyBatis does support dynamic SQL in the nature you need. The big trick, is to use ${variable} instead of #{variable}. Just be careful, it leaves you susceptible to SQL injection attacks. When using # MyBatis uses PreparedStatements to avoid SQL injection, and then
So take for example example, you had a Mapper interface with method.
ComplexObject selectSomeObject(@Param("columnName") String columnName);
Your SQL map could use the parameter in part of the actual select code.
i.e.
<select id="selectSomeObject" resultType="someObject">
select t1.column as ${columnName}
from table1 t1
</select>
If you need a global variable, check out this question. MyBatis - defining a global parameter
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow