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

我们再看看官网怎么说:

相关推荐
笨手笨脚の23 分钟前
设计模式-迭代器模式
java·设计模式·迭代器模式·行为型设计模式
spencer_tseng1 小时前
Eclipse 4.7 ADT (Android Development Tools For Eclipse)
android·java·eclipse
lubiii_1 小时前
SQLMap常用命令指南(参数及其用法)
sql·web安全·网络安全
聪明的笨猪猪2 小时前
Java Spring “AOP” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
seven97_top3 小时前
Springboot 常见面试题汇总
java·spring boot·后端
小蕾Java3 小时前
Java 开发工具,最新2025 IDEA 使用,保姆级教程
java·开发语言·intellij-idea
刘登辉3 小时前
idea使用联网缓存的pom进行离线开发
java·ide·intellij-idea·离线开发
Автомата Калашникова3 小时前
Java操作.docx文档 —— docx4j
java·开发语言
hello 早上好4 小时前
深入 Spring 条件化配置底层:从硬编码到通用注解的实现原理
java·后端·spring
亚林瓜子4 小时前
Spring中Date日期序列化与反序列化中格式设置
java·后端·spring·jackson·date