动态sql的if判断很常用,非常便捷方便,下面记录一个坑。
判断空和空值
一般情况下,动态sql的if判断字符串,我们的习惯是用来判断null和 ’ ',外层用双引号,内层单引号,例如:
<if test=" _sort !=null and _sort != ''">
order by ${_sort}
<if test="_order !=null and _order != ''">
${_order}
</if>
</if>
判断具体值
但是,有时候需要对判断条件的值进行对比,若符合某个值相等则增加某些条件,这时候,外层双引号,内层单引号会出错,例如:
<if test="departmentName == '0'">
and a.first_name ='内科'
</if>
<if test="departmentName == '1'">
and a.first_name ="外科"
</if>
<if test="departmentName == '2'">
and a.first_name !='外科' and a.first_name !='内科'
</if>
正确的表达是外层单引号,内层双引号:
<if test='departmentName == "0"'>
and a.first_name ='内科'
</if>
<if test='departmentName == "1"'>
and a.first_name ="外科"
</if>
<if test='departmentName == "2"'>
and a.first_name !='外科' and a.first_name !='内科'
</if>