mybatis的if判断语句其实跟el表达式的if条件判断有些类似。

例如: <if test="id != null"> </if>

1 如果参数为数字类型的时候没有特殊需求的情况只需要判断是否为null即可。

例如:<if test="id != null"></if>

 如果有特殊需求,例如判断是否大于某个数的时候才行。只需要加上对应的条件判断即可

例如:<if test='id != null and id > 28'></if>

 mybatis对于这种大于小于等等还有另一种形式。

例如:<if test='id != null and id gt 28'></if>

对应关系:

---------------------------------------

    gt            对应             >

    gte         对应              >=

    lt             对应              <(会报错  相关联的 "test" 属性值不能包含 '<' 字符)

    lte          对应               <=(会报错  相关联的 "test" 属性值不能包含 '<' 字符)

---------------------------------------

2 如果为字符串类型

2.1 如果不需要过滤空串的情况 仅仅判断null即可

例如:<if test="username != null"></if>

2.2 如果需要过滤空串,添加空串判断即可  不支持 &&   所以这里用 and  or  || 来做逻辑与或的判断 

例如:<if test="username != null and '' != username"></if> 或者 <if test="username != null and ''  neq username"></if>

2.3 如果判断字符串是否已某个特殊字符开头,结尾等。直接调用String的对应方法即可

例如:<if test="username != null and username.indexOf('ji') == 0"> </if> <!-- 是否以什么开头 -->
    <if test="username != null and username.indexOf('ji') >= 0"> </if> <!-- 是否包含某字符 -->
    <if test="username != null and username.lastIndexOf('ji') > 0"></if>  <!-- 是否以什么结尾 -->

2.4 是否是某个特定字符串,某些业务有此需要。

例如:<if test="username != null and 'hello' == username"></if> 或者<if test="username != null and 'hello' eq username"></if>

注意:

<if test="username != null and 'hello' == username"></if>这种形式的写法在参数类型是字符串的时候是没有问题的,

但是参数类型为非字符串类型的时候就需要写成 <if test="username != null and 'hello'.toString() == username.toString()"></if>

仅仅写成<if test="username != null and 'hello'.toString() == username"></if>也会有很大可能会挂。

也许你会说非字符串的为什么要写成这样。这就要看特殊需要了。

例如:某一个sql片段是公用的,

<if test="username != null"></if>
<if test="password != null"></if>

该片段更新条件也用,但是当你需要将某一个字段更新成null的时候怎么办。

这个时候就可以通过传入一个特定的字符串来弄。当传入的字符串为特定字符串的时候就更新该字符串为null。

<if test="username != null and 'hello'.toString() == username.toString()">xxx=null</if>

当然这样子貌似date型会挂。

通过 2.2 也可以看出mybatis对于字符串的相等不相等的判断也是有对应的特殊操作符的。

-------------------------------------------------------

eq                  对应                ==

neq               对应                 !=

------------------------------------------------------

当然还可以看出来if的条件判断test是支持对象自身方法调用的,即使是自己写的方法,可以自己尝试。当然下面会有例子。

例如:里面可以用‘xxxx’.equals(xxxx) 字符串的比较两个字符串方法

    xxxx.indexOf('ss') 判断字符串里面是否包含某个字符等等  

 3 判断list是否为空

上面说过,if条件判断可以直接调用对象自身的方法进行逻辑判断,所以list判空。可以调用.size()>0或者.isEmpty()

例如:<if test="userList != null and userList.isEmpty()"></if> , <if test="userList != null and userList.size()>0"></if>

4 map参数同同理  取值的话 map.key(map中的key名字)即可