ibatis - MyBatis -Where 子句中的嵌套条件

标签 ibatis mybatis

我在 MyBatis v3 映射器 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 

最佳答案

您可以尝试将该部分封装在 <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>

关于ibatis - MyBatis -Where 子句中的嵌套条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14306949/

相关文章:

java - Ibatis queryWithRowHandler() 似乎仍然获取所有行

java - 在 ibatis 中是否可以在同一个插入查询中有多个 selectKey 子句?

java - 使用多个IN OUT参数和注释调用MyBatis中的存储过程

mysql - MyBatis 数据映射。收藏。关系表

java - Camel mybatis 组件仅支持列表参数,该参数必须命名为 'list' ?

java - 用 MyBatis 映射树?

java - iBatis 是动态 SQL 查询的正确选择吗?

java - iBatis,spring,如何记录执行的sql?

java - Mybatis Spring多数据库Java配置

java - 如果我使用 myBatis 从几乎相同的表中提取时如何删除大量重复代码