Mybatis条件筛选<if>使用和where 1=1小技巧

Mybatis条件筛选使用和where 1=1小技巧

最近用mybatis做项目数据库框架,学习了很多知识,今天分享两个小知识:


关于if标签的使用

我们在做业务时,经常遇到按照条件查询,例如:

我们要根据年龄和性别筛选出用户列表
我们通常会这样写
select * from user where age=#{age} and sex=#{sex}
后来我们又增加了一个新需求:
我们还想通过年龄来筛选用户,当有性别条件时,需要根据年龄和性别筛选
使用mybatis的if标签就可以实现了
我们可以这样写:

select * from user where age=#{age} 
<if test="sex!=null">
    and sex=#{sex}
 </if>

后来我们又有了新需求:
如果接口传入了性别,就根据性别筛选,如果传入了年龄,就根据年龄筛选,如果两者都有,需要根据两者一起筛选,如果两者没有,不带筛选条件。
这下可就难住了写sql的小伙伴了,where 改放在什么位置,怎么写,sql才不会报错。
下面就有了where 1=1小技巧

where 1=1小技巧

有了它我们就可以这样写:

select * from user where  1=1
<if test="sex!=null">
    and sex=#{sex}
</if>
<if test="age!=null">
    age=#{age}
</if>

至此,搞定了联合条件筛选的需求,深受小伙伴的喜爱。

猜你喜欢

转载自blog.csdn.net/u012489412/article/details/80512543