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

我们再看看官网怎么说:

相关推荐
带刺的坐椅几秒前
jFinal 使用 SolonMCP 开发 MCP(拥抱新潮流)
java·ai·solon·jfinal·mcp
陌尘(MoCheeen)20 分钟前
技术书籍推荐(002)
java·javascript·c++·python·go
牛马baby22 分钟前
Java高频面试之并发编程-16
java·开发语言·面试
cainiao08060522 分钟前
《Spring Boot 4.0新特性深度解析》
java·spring boot·后端
zizisuo33 分钟前
面试篇:Spring MVC
java·spring·mvc
-曾牛33 分钟前
Spring AI 与 Hugging Face 深度集成:打造高效文本生成应用
java·人工智能·后端·spring·搜索引擎·springai·deepseek
Brookty1 小时前
【Java学习】Lambda表达式
java·学习
孤寂大仙v1 小时前
【Linux笔记】——进程信号的保存
java·linux·笔记
饕餮争锋1 小时前
feign.RequestInterceptor 简介-笔记
java·开发语言·笔记
计算机学姐1 小时前
基于SpringBoot的小区停车位管理系统
java·vue.js·spring boot·后端·mysql·spring·maven