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 小时前
【MySQL 数据库】复合查询
android·数据库·mysql
Elastic 中国社区官方博客1 小时前
Elasticsearch:为 AI Agent builder 创建 skill plugin
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
Data_Journal1 小时前
2026年十大数据集网站
大数据·开发语言·数据库·人工智能·python
珠海西格电力1 小时前
如何实现零碳园区管理系统“云-边-端”架构的协同
大数据·数据库·人工智能·架构·能源
XS0301061 小时前
JDBC实现数据库增删改查
数据库
茉莉玫瑰花茶1 小时前
LangGraph 入门教程:构建 AI 工作流 [ 案例一 ]
数据库
宸凉1 小时前
Oracle 19C的安装
数据库·oracle
YL200404262 小时前
MySQL-基础篇-约束
数据库·mysql
麦聪聊数据2 小时前
SQL与数据库开发(五):纯 SQL 解决“连续签到”与“用户留存”问题
数据库·sql·数据库开发