Mybatis <where>标签的小问题

我们都知道Mybatis的<where>标签是可以自动去掉子句第一个and或者or的,具体如下:

XML 复制代码
 <select id="selectSelective" resultType="com.study.entity.User">
    select * from t_user
    <where>
      <if test="name != null and name != ''">
        and name = #{name}
      </if>
      <if test="sex != null and sex != ''">
        and sex = #{sex}
      </if>
    </where>
  </select>

如果没有<where>的时候,我们如果name条件满足,就会出现如下的SQL语句:

sql 复制代码
select * from t_user where and name = 'CLAY';

很明显看出多了一个and,那么加上<where>标签,它就会为我们自动去掉这个and,也就是第一个and。

那我们明白了这个前提,我们再看下一个SQL:

XML 复制代码
 <select id="selectSelective" resultType="com.study.entity.User">
    select * from t_user
    <where>
      del_flag = '0'
      <if test="name != null and name != ''">
        and name = #{name}
      </if>
      <if test="sex != null and sex != ''">
        and sex = #{sex}
      </if>
    </where>
  </select>

那按我们刚才说的,<where>会去掉第一个and,那这个SQL语句不就变成了下面这样吗:

sql 复制代码
select * from t_user where del_flag = '0' name = 'CLAY';

但其实结果并没有去掉这个and,还是正常的:

sql 复制代码
select * from t_user where del_flag = '0' and name = 'CLAY';

这是因为<where>标签去掉的是紧贴着where后面的and或者or,中间隔一个单词都不行。

我们再看看官网怎么说:

相关推荐
艾伦~耶格尔2 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
爪洼传承人2 小时前
18- 网络编程
java·网络编程
smileNicky2 小时前
SpringBoot系列之从繁琐配置到一键启动之旅
java·spring boot·后端
吃掉你也没关系吧2 小时前
【postgresql】一文详解postgresql中的统计模块
sql·postgresql
祈祷苍天赐我java之术2 小时前
Java 迭代器(Iterator)详解
java·开发语言
David爱编程3 小时前
为什么必须学并发编程?一文带你看懂从单线程到多线程的演进史
java·后端
我命由我123453 小时前
软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)
java·开发语言·javascript·设计模式·java-ee·策略模式·js
long3163 小时前
java 策略模式 demo
java·开发语言·后端·spring·设计模式
摇滚侠3 小时前
HTML <iframe> 标签 如何把html写入iframe标签
java
云间月13144 小时前
飞算JavaAI:从智能调度到出行服务的全链路技术升级
java·redis·飞算javaai炫技赛