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关键字;
  • 自动去除子句开头多余的AND或OR,避免语法错误。

优化后的多条件查询:

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关键字,自动去除多余逗号 动态更新语句
相关推荐
Omics Pro7 分钟前
之江实验室NAR|虚拟细胞3阶段训练范式
数据库·人工智能·算法·机器学习·自然语言处理
龙亘川12 分钟前
探索智慧文化服务:建设初衷、整体架构、技术支撑、发展现状与实践影响
大数据·数据库·架构
风早爽太16 分钟前
Python 学习笔记:数据库迁移工具 ‌Alembic
数据库·python·fastapi·alembic
2501_9336707932 分钟前
2027风控策略岗秋招准备:SQL、Excel、建模的优先级与项目路径
人工智能·sql·excel
java1234_小锋34 分钟前
【技术专题】Mysql8 数据库 - Mysql8 数据库基本操作
数据库·mysql
其实防守也摸鱼1 小时前
DeepSeek Harness 开源贡献手记:从 Issue 到 Merge 的完整旅程
android·数据库·学习·ai·oracle·自动化
jason.zeng@15022071 小时前
canal做mysql的异步传输工具
数据库·mysql·linq
Ivanqhz1 小时前
BURG(自底向上重写生成器)
服务器·数据库·人工智能·深度学习·算法
仍然.1 小时前
Redis---主从复制
java·数据库·redis
其实防守也摸鱼2 小时前
网安自测题:掌握核心知识点的实用练习
linux·运维·服务器·前端·数据库·sql·xss