spring boot --07

一、什么是动态 SQL?

动态 SQL 是指随着用户输入或外部条件变化而动态拼接、生成的 SQL 语句,主要用于解决多条件查询、动态更新等场景,避免写大量重复的固定 SQL 语句。


二、核心标签详解

1. <if> 标签

作用 :用于条件判断,当test属性中的条件为true时,才会拼接标签内的 SQL 片段。语法示例

xml

复制代码
<if test="name != null">
    name like concat('%', #{name}, '%')
</if>

多条件查询示例

xml

复制代码
<select id="list" resultType="com.itheima.pojo.Emp">
    select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time 
    from emp
    where
    <if test="name != null">
        name like concat('%', #{name}, '%')
    </if>
    <if test="gender != null">
        and gender = #{gender}
    </if>
    <if test="begin != null and end != null">
        and entrydate between #{begin} and #{end}
    </if>
    order by update_time desc
</select>

⚠️ 注意:如果所有<if>条件都不满足,where关键字后会没有条件,导致 SQL 语法错误,此时需要配合<where>标签使用。


2. <where> 标签

作用

  • 仅当子标签(如<if>)有内容时,才会插入WHERE关键字;
  • 自动去除子句开头多余的ANDOR,避免语法错误。

优化后的多条件查询

xml

复制代码
<select id="list" resultType="com.itheima.pojo.Emp">
    select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time 
    from emp
    <where>
        <if test="name != null">
            name like concat('%', #{name}, '%')
        </if>
        <if test="gender != null">
            and gender = #{gender}
        </if>
        <if test="begin != null and end != null">
            and entrydate between #{begin} and #{end}
        </if>
    </where>
    order by update_time desc
</select>

3. <set> 标签

作用

  • 动态插入SET关键字;
  • 自动去除更新语句中多余的逗号,避免语法错误,常用于动态更新场景。

动态更新示例:需求:更新员工信息时,只更新用户传递了值的字段,未传递的字段不更新。

xml

复制代码
<update id="update">
    update emp
    <set>
        <if test="username != null">username = #{username},</if>
        <if test="name != null">name = #{name},</if>
        <if test="gender != null">gender = #{gender},</if>
        <if test="image != null">image = #{image},</if>
        <if test="job != null">job = #{job},</if>
        <if test="entrydate != null">entrydate = #{entrydate},</if>
        <if test="deptId != null">dept_id = #{deptId},</if>
        <if test="updateTime != null">update_time = #{updateTime}</if>
    </set>
    where id = #{id}
</update>

对比:如果不使用<set>标签,直接在set后写多个<if>,可能会出现最后一个字段后多余逗号的语法错误。


三、核心标签对比表

表格

标签 核心作用 典型使用场景
<if> 条件判断,动态拼接 SQL 片段 多条件查询、动态更新、动态插入
<where> 动态插入WHERE关键字,自动去除开头的AND/OR 多条件查询语句
<set> 动态插入SET关键字,自动去除多余逗号 动态更新语句
相关推荐
倔强的石头_1 小时前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库
zzzzzz3101 天前
9K Star 炸裂开源!这个 C 语言写的代码知识图谱,把 Linux 内核索引压缩到了 3 分钟
linux·服务器·sql
倔强的石头_3 天前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
云技纵横3 天前
唯一索引 INSERT 死锁实战:5 秒复现交叉插入的 S 锁循环等待
sql·mysql
冬奇Lab3 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLite
数据库·人工智能·llm
ClouGence4 天前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
无响应de神4 天前
三、用户与权限管理
数据库·mysql
麦聪聊数据5 天前
数据服务化时代:企业数据能力输出的核心路径
数据库
shushangyun_5 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
DARLING Zero two♡5 天前
【MySQL数据库】数据类型与表约束
数据库·mysql