Mybatis where 标签

<where> 标签动态的决定是否需要添加 WHERE 条件语句。

例如下面的代码,

<select id="searchUserAll" resultType="com.cr.Pojo.UserInfo" >
    select *
    from  userinfo
    <where>
        <if test="phoneNumber != null and !&quot;&quot;.equals(phoneNumber.trim())">
            and phoneNumber=#{phoneNumber}
        </if>
    </where>
</select>

如果 <if> 标签中 test 的值为 false ,<where> 标签中将不会有值,也就没有 where 条件语句,因此生成的 SQL 语句是:

select *
from  userinfo

如果为 true ,生成的 SQL 语句就将含有 where 条件语句,如果开头为 and 或 or ,它们将被自动的去除。最后生成的 SQL 语句是这个样子:

select *
from  userinfo
where phoneNumber=#{phoneNumber} 

使用<where>标签避免了如

select *
from  userinfo
where

select *
from  userinfo
where and phoneNumber=#{phoneNumber}  

这样的错误。

发布了34 篇原创文章 · 获赞 18 · 访问量 2946

猜你喜欢

转载自blog.csdn.net/weixin_40608613/article/details/103217548