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,中间隔一个单词都不行。

我们再看看官网怎么说:

相关推荐
lee_curry2 分钟前
第四章 jvm中的垃圾回收器
java·jvm·垃圾收集器
xcLeigh1 小时前
KES数据库性能优化实战
数据库·sql·性能优化·sql优化·数据性能
九转成圣1 小时前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json
直奔標竿2 小时前
Java开发者AI转型第二十七课!Spring AI 个人知识库实战(六)——全栈闭环收官,解锁前端流式渲染终极技巧
java·开发语言·前端·人工智能·后端·spring
金銀銅鐵2 小时前
[java] 编译之后的记录类(Record Classes)长什么样子(上)
java·jvm·后端
野生技术架构师4 小时前
金三银四面试总结篇,汇总 Java 面试突击班后的面试小册
java·面试·职场和发展
小袁拒绝摆烂4 小时前
多表关联大平层转JSON树形结构
java·json
ja哇5 小时前
大厂面试高频八股
java·面试·职场和发展
yoyo_zzm6 小时前
Laravel6.x新特性全解析
java·spring boot·后端