Mybatis解决多条件查询不能得到正确SQL的两种方法 恒等式 where标签

在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,从而查询不到任何结果

使用if标签初步解决问题

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语法

那么怎么办呢,我们可以用恒等式的方法暴力解决这个问题

使用恒等式1=1暴力解决问题,但是并不优雅

我们可以给所有的条件里面都加一个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>

上述代码的确不会报错,但是并不优雅,有没有更加优雅的方法呢?

where标签自动得到正确的SQL语句

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>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值