MyBatis - Where子句中的嵌套条件

时间:2013-01-13 18:54:00

标签: ibatis mybatis

我在MyBatis v3 mapper xml中动态生成where子句。但放置括号真的很麻烦。是否有一种更简单的方法来处理问题而不使用if语句?

<where>
  <if test="filter != null">
    <choose>
      <when test="filter.lref != null">
        file.lref = #{filter.lref}
      </when>
      <otherwise>
        <!-- I don't want to use this -->
        <if test="filter.forLike != null || filter.forInt != null">
          ( 
        </if>
        <if test="filter.forLike != null" >
          subject LIKE #{filter.forLike}    
          OR requester_identifier LIKE #{filter.forLike}
          OR requester_name LIKE #{filter.forLike}
        </if>
        <if test="filter.forInt != null">
          OR file_id = #{filter.forInt}
        </if>

        <!-- I don't want to use this -->
        <if test="filter.forLike != null || filter.forInt != null">
          ) 
        </if>
      </otherwise>
    </choose>
  </if>
  <if test="listMode > 0">
    <choose>
       <when test="listMode == 1">
         AND file_status_link.dosya_ref is not NULL
       </when>
       <otherwise>
         AND file_status_link.dosya_ref is NULL
       </otherwise>
    </choose>
   </if>            
</where>

示例动态生成的SQL输出如下

WHERE ( subject LIKE ? OR requester_identifier LIKE ? OR requester_name LIKE ? ) 
AND file_status_link.dosya_ref is NULL 

2 个答案:

答案 0 :(得分:5)

您可以尝试将该部分封装在<trim>标记内。它会是这样的:

<trim prefix="(" prefixOverrides="OR" suffix=")">
  <if test="filter.forLike != null" >
    subject LIKE #{filter.forLike}    
    OR requester_identifier LIKE #{filter.forLike}
    OR requester_name LIKE #{filter.forLike}
  </if>
  <if test="filter.forInt != null">
    OR file_id = #{filter.forInt}
  </if>
</trim>

答案 1 :(得分:0)

伪SQL(XML-SQL):

where
    1 = 1
    <A>and file.lref = #{filter.lref}</A>
    <D>and (
        <E>
        subject like #{filter.forLike}    
        or requester_identifier like #{filter.forLike}
        or requester_name like #{filter.forLike}
        </E>
        <F>or file_id = #{filter.forInt}</F>
    )</D>
    </B>
    <C>and file_status_link.dosya_ref is <G>not</G> null</C>

其中:

A: <B> && filter.lref != null
B: filter != null
D: <B> && (<E> || <F>)
E: filter.forLike != null
F: filter.forInt != null
C: listMode > 0
G: listMode == 1