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>),否则可能降低可读性。
相关推荐
爱吃苹果的梨叔2 小时前
训练集群网络中断怎么办?智算机房的 Console 串口排障方案
网络·python·智能路由器·php
李妍.6 小时前
02Numpy基础(上)
开发语言·python
TheBestRucy6 小时前
Python 九阳神功之贰:面向对象(下)
开发语言·python
2601_965958466 小时前
口腔黏膜脱皮超2周未愈建议及时就医
人工智能·python
AI_小站6 小时前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
微小冷7 小时前
在不同空间中展示数据(欧式、球面、庞加莱圆盘)
python·双曲空间·微分几何·geomstats·庞加莱圆盘·球面
felixking7 小时前
C++20 协程
开发语言·c++·协程
weixin_431600448 小时前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
讲温控就好了8 小时前
从医疗影像到能源存储——芯片冷却温控技术的跨行业赋能
人工智能·python·能源
面对疾风叭!哈撒给8 小时前
Windows 11 系统更新操作设置停止更新的时间
windows