Is there some way to check if a property in include fragment has been set? Example:
<include refid="myFilterLocation">
<property name="model" value="model_name"/>
...
...
...
</include>
And then when this fragment is used:
<if test="....">
AND ${model}= #{${param}.model,jdbcType=VARCHAR}
</if>
Is there some way to test if the property is not sent?. I want not send properties if I do not want to filter in my query.
Kind regards.
When the property is not defined, ${model}
is not replaced at all, so you may be able to write the condition as follows.
<if test='"${model}" != "\${model}"'>
AND ${model}= #{${param}.model,jdbcType=VARCHAR}
</if>
Note the unusual usage of single/double quotes and the backslash before the second dollar sign.
(Longer explanation)
There are two variables ${model}
in the test
attribute value, however the second one is escaped using a leading backslash.
So, when the 'model' property is specified, the included if element will look as follows.
<if test='"model_name" != "${model}"'>
The condition is a simple two strings comparison and the result is true
.
Note that the backslash used to escape the variable is removed (that's how MyBatis' variable escaping works).
Now, when the 'model' property is not specified, the variable is not replaced, so the if element looks as follows after the inclusion.
<if test='"${model}" != "${model}"'>
As you can see, the two strings are the same and the result of the condition is false
.
And OGNL requires double quotes for string literal.
If you use single quotes, NumberFormatException
may be thrown (OGNL recognizes it as a char
, it seems).