MyBatis-条件子句中的嵌套条件 [英] MyBatis - Nested Conditions in Where Clause
本文介绍了MyBatis-条件子句中的嵌套条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在MyBatis v3映射器xml中动态生成where子句.但是,放置括号确实很麻烦.有没有不使用if语句就可以解决问题的简便方法?
I'm dynamically generating the where clause inside MyBatis v3 mapper xml. However placing parentheses is really cumbersome. Is there an easier way to handle the problem without using if statements?
<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输出示例如下
Sample dynamically generated SQL output is as follows
WHERE ( subject LIKE ? OR requester_identifier LIKE ? OR requester_name LIKE ? )
AND file_status_link.dosya_ref is NULL
推荐答案
您可以尝试将该部分封装在<trim>
标记内.会是这样的:
You can try to encapsulate that part inside <trim>
tag. It would be something like this:
<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>
这篇关于MyBatis-条件子句中的嵌套条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文