Solution to the ineffectiveness of mybatis if tag judgment

  • 2021-08-17 00:00:03
  • OfStack

Actual demand


<if test="computationRule == '1'">
  FROM app_sz_bbb a
</if>
<if test="computationRule == '2'">
  FROM app_ccc a
</if>

This situation does not take effect,

Reason: mybatis is resolved by OGNL expression. In OGNL expression, '0' will be resolved into characters, java is strongly typed, char and one string will cause inequality, so sql in if tag will not be resolved.

Let's talk about how to solve it first

3 species:

Add. toString ()


<if test="computationRule == '1'.toString()">
  FROM app_sz_bbb a
</if>
<if test="computationRule == '2'.toString()">
  FROM app_ccc a
</if>

choose when Tag Replacement


<choose>
   <when test="computationRule == '1'">
   FROM app_sz_bbb a
   </when>
   <otherwise>
     FROM app_sz_bbb a
   </otherwise>
 </choose>

Replace single quotation marks with double quotation marks


<if test='computationRule == "1"'>
  FROM app_sz_bbb a
</if>
<if test='computationRule == "2"'>
  FROM app_ccc a
</if>

if tag judgment string in MyBatis does not take effect

mapper file for exception sql:


<if test="isBound != null and isBound !='' and isBound == '1'">
  and box_sid is not null 
</if>
<if test="isBound != null and isBound !='' and isBound == '2'">
  and box_sid is null 
</if>

mapper file for correct sql


<if test="isBound != null and isBound !='' and isBound == '1'.toString()">
  and box_sid is not null 
</if>
<if test="isBound != null and isBound !='' and isBound == '2'.toString()">
  and box_sid is null 
 </if>

Related articles: