mybatis中<where>标签使用场景

    <select id="queryBlogIf" resultType="blog" parameterType="map">
        select * from mybatis.blog where
        <if test="title!=null">
            title like concat('%',#{title},'%')
        </if>
        <if test="author!=null">
            and author = #{author}
        </if>

    </select>

正常使用if标签应该是这样的,但是这样会导致一个问题。

就是在只查询author的时候,mybatis不会自动的去除掉 and,而导致SQL语句变成

select * from mybatis.blog where and author = ?

这样就会出问题

<where>标签正是用来解决这个问题的, 如果是第一个条件不满足,匹配后面的条件,它会自动的去除后面条件中的and符号。

    <select id="queryBlogIf" resultType="blog" parameterType="map">
        select * from mybatis.blog
        <where>
            <if test="title!=null">
                title like concat('%',#{title},'%')
            </if>
            <if test="author!=null">
                and author = #{author}
            </if>
        </where>


    </select>

如果不传递参数的话,where也会去掉。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值