需求
where语句中的值可以为null,也可以不为null
解决
方案一:
使用<if>
标签
<select id = "" resultMap = "">
select *
from table
<where>
<if test="item != null">
and item = #{item}
</if>
<if test="item == null">
and item IS NULL
</if>
</where>
</select>
方案二:
使用<choose>
<when>
<otherwise>
标签
<select id = "" resultMap = "">
select *
from table
<where>
<when test="item != null">
and item = #{item}
</when>
<otherwise>
and item IS NULL
</otherwise>
</where>
</select>
重要的一点是 <when>
与<otherwise>
标签一定要在<choose>
内部使用;
<choose>
标签是按照顺序(可以有多个 <when>
)判断内部 <when>
标签中的test条件判断出是否成立,如果有一个成立,则<choose>
结束,当所有 <when>
条件都不满足时,则执行<otherwise>
中的sql