在Mybatis编写多条件查询语句中,我们经常采用下面的写法
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
where status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName};
select>
上述代码同时查询status,company_name和brand_name这三个条件是否满足要求,如果这三个条件同时存在的话是可以正常运行的,但是如果其中有一个条件没有值为空,比如我只查询company_name和brand_name这两个条件,那么第一个status就会赋值为null,从而查询不到任何结果
Mybatis想到了这个问题,提供了一个if标签来解决问题,你不就是怕不是所有条件都会有值吗,那么加上条件就好了,就比如如果status为null的话,那么就不添加这个条件,写在代码里就是下面的代码
if标签的主要功能就是判断一个条件是否为空
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
where
<if test="status != null">
status = #{status}
if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
if>
<if test="brandName != null and companyName != '' ">
and brand_name like #{brandName};
if>
select>
上述代码如果不填company_name和brand_name都是可以正常工作的,但是如果你不填status就不能正常工作了,因为如果status=null的话,where后面直接跟and,这是一个错误的sql语法
那么怎么办呢,我们可以用恒等式的方法暴力解决这个问题
我们可以给所有的条件里面都加一个and,再在where后面带上一个1=1
这样不管我们选择哪几个条件都能得到正确的SQL语句,恒等式解决问题的代码如下
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
where 1 = 1
<if test="status != null">
and status = #{status}
if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
if>
<if test="brandName != null and companyName != '' ">
and brand_name like #{brandName};
if>
select>
上述代码的确不会报错,但是并不优雅,有没有更加优雅的方法呢?
Mybatis除了提供了上述的if标签,同时还有一个where标签,我们只需要把所有的查询条件都放入这个where标签就能永远得到正确的SQL语句,因为内部已经处理好了
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
<where>
<if test="status != null">
and status = #{status}
if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
if>
<if test="brandName != null and companyName != '' ">
and brand_name like #{brandName};
if>
where>
select>