4

我在 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 
4

2 回答 2

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>
于 2013-01-13T20:46:38.817 回答
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
于 2014-05-10T11:06:42.320 回答