mybatis 动态sql之if条件判断

mybatis 动态sql之if条件判断

1. 如果参数为数字类型

<if test=id != null and id > 28></if>

gt 对应 > gte 对应 >= lt 对应 <(会报错 相关联的 “test” 属性值不能包含 ‘<’ 字符) lte 对应 <=(会报错 相关联的 “test” 属性值不能包含 ‘<’ 字符) 2.如果为字符串类型 如果需要过滤空串,添加空串判断即可 不支持 && 所以这里用 and or || 来做逻辑与或的判断

<if test="username != null and  != username"></if> 
或者 
<if test="username != null and  neq username"></if>

如果判断字符串是否已某个特俗字符开头,结尾等。直接调用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>  <!-- 是否以什么结尾 -->

是否是某个特定字符串

<if test="username != null and hello == username"></if> 或者<if test="username != null and hello eq username"></if>

注意:这种形式的写法在参数类型是字符串的时候是没有问题的, 但是参数类型为非字符串类型的时候就需要写成:

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

eq 对应 == neq 对应 != 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名字)即可 也自己写一个方法,在if里面使用,自己定义一个类,里面一个方法用于条件判断用。

<if test="dynamicSql1Model.getMySelfMethod()">
dynamicSql1Model为自定义的类,getMySelfMethod()是自定义类里面的自定义方法
经验分享 程序员 微信小程序 职场和发展