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

我们再看看官网怎么说:

相关推荐
lifallen17 小时前
从Apache Doris 学习 HyperLogLog
java·大数据·数据仓库·算法·apache
fire-flyer17 小时前
maven-jlink-plugin入门
java·maven
养生技术人17 小时前
Oracle OCP认证考试题目详解082系列第49题
运维·数据库·sql·oracle·database·开闭原则·ocp
Knight_AL17 小时前
Java 单元测试全攻略:JUnit 生命周期、覆盖率提升、自动化框架与 Mock 技术
java·junit·单元测试
cominglately17 小时前
记录一次生产环境数据库死锁的处理过程
java·死锁
white-persist17 小时前
SQL 注入详解:从原理到实战
前端·网络·数据库·sql·安全·web安全·原型模式
用户03321266636717 小时前
在 Word 文档中插入图片的 Java 指南
java
深圳蔓延科技17 小时前
单点登录到底是什么?
java·后端
SimonKing17 小时前
除了 ${},Thymeleaf 的这些用法让你直呼内行
java·后端·程序员
科兴第一吴彦祖17 小时前
基于Spring Boot + Vue 3的乡村振兴综合服务平台
java·vue.js·人工智能·spring boot·推荐算法