spring boot--08

一、<foreach> 标签:批量操作神器

1. 核心作用

用于遍历集合,批量生成 SQL 片段,最常见的场景是批量删除(IN语句)、批量插入

2. 批量删除示例

业务场景:员工列表的批量删除

sql

复制代码
-- 原生SQL
delete from emp where id in (1,2,3);
1)Mapper 接口方法

java

运行

复制代码
// 批量删除方法,接收id列表
public void deleteByIds(List<Integer> ids);
2)XML 映射文件

xml

复制代码
<delete id="deleteByIds">
    delete from emp where id in
    <foreach collection="ids" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
</delete>

3. 标签属性详解

表格

属性 说明
collection 要遍历的集合参数名,这里对应接口方法的参数ids
item 遍历集合时,每个元素的别名(这里用id代表列表中的单个 ID)
separator 元素之间的分隔符,这里用逗号分隔,生成1,2,3
open 遍历开始前拼接的片段,这里是(,和IN语句的括号对应
close 遍历结束后拼接的片段,这里是),闭合IN语句的括号

二、<sql><include> 标签:SQL 片段复用

1. 核心作用

  • <sql>:定义可重复使用的 SQL 片段,避免代码冗余;
  • <include>:通过refid引用定义好的 SQL 片段。

2. 代码示例

1)定义可复用 SQL 片段

xml

复制代码
<!-- 定义通用的查询字段片段 -->
<sql id="commonSelect">
    select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time 
    from emp
</sql>
2)在多个查询中引用

xml

复制代码
<!-- 条件查询 -->
<select id="list" resultType="com.itheima.pojo.Emp">
    <include refid="commonSelect"/>
    <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>

<!-- 根据ID查询 -->
<select id="getById" resultType="com.itheima.pojo.Emp">
    <include refid="commonSelect"/>
    where id = #{id}
</select>

三、注意事项与最佳实践

  1. <foreach>collection参数

    • 如果接口方法的参数是List类型,collection属性值可以写list或直接写参数名(如示例中的ids);
    • 如果是Array数组类型,collection属性值写array或参数名。
  2. 批量删除的性能建议

    • 单次批量删除的数量不宜过大,避免生成过长的IN语句,影响数据库性能;
    • 超大规模批量删除建议分批次执行。
  3. <sql>片段复用

    • 适合复用查询字段、表名等固定 SQL 片段,提升代码可维护性;
    • 片段内避免包含动态 SQL(如<if>),否则可能降低可读性。
相关推荐
卷毛的技术笔记1 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
编程大师哥1 小时前
匿名函数 lambda + 高阶函数
java·python·算法
isyangli_blog1 小时前
OpenDayLight (Carbon 版本) 启动与组件安装
开发语言·php
vb2008111 小时前
FastAPI APIRouter
开发语言·python
Benszen1 小时前
KVM虚拟化解决方案
开发语言·perl
会编程的土豆1 小时前
Go 语言反射(Reflection)详解
开发语言·后端·golang
東雪木1 小时前
多线程与并发编程 专属复习笔记
java·开发语言·笔记·java面试
adrninistrat0r1 小时前
Java调用链MCP分析工具
java·python·ai编程
杨充2 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
噜噜噜阿鲁~2 小时前
python学习笔记 | 11.3、面向对象高级编程-多重继承
java·开发语言