参考这个sql
<update id="updateDeptChildren" parameterType="java.util.List"> update sys_dept set ancestors =
<foreach collection="depts" item="item" index="index" separator=" " open="case dept_id" close="end"> when #{item.deptId} then #{item.ancestors} </foreach>
where dept_id in
<foreach collection="depts" item="item" index="index" separator="," open="(" close=")"> #{item.deptId} </foreach> </update>
上述示例是一个 MyBatis 的 `<update>` 元素的配置,用于更新 `sys_dept` 表中的记录。以下是对该配置的解释:
- `<update id="updateDeptChildren" parameterType="java.util.List">`:定义了一个名为 `updateDeptChildren` 的更新操作,输入参数类型为 `java.util.List`。
- `update sys_dept set ancestors =`:指定要更新的表和要更新的字段。
- `<foreach>` 元素用于循环遍历输入的 `depts` 列表,并根据其中的元素动态生成 SQL 语句。
- 第一个 `<foreach>` 元素用于生成更新语句的 `case` 部分。它遍历 `depts` 列表中的每个元素,并根据元素的 `deptId` 和 `ancestors` 属性生成 `case` 语句。每个 `when` 子句表示当 `deptId` 匹配时,将 `ancestors` 值更新到 `sys_dept` 表的 `ancestors` 字段。
- 第二个 `<foreach>` 元素用于生成更新语句的 `where` 部分。它遍历 `depts` 列表中的每个元素,并生成 `dept_id` 的 `IN` 条件,以将更新限制为指定的 `deptId` 值。
请注意,`<foreach>` 元素的属性说明如下:
- `collection`:指定要遍历的集合或数组。
- `item`:指定在遍历过程中当前元素的别名。
- `index`:指定在遍历过程中当前元素的索引(可选)。
- `separator`:指定在每次迭代之间添加的分隔符。
- `open`:指定在循环的开头添加的文本。
- `close`:指定在循环的结尾添加的文本。
通过以上配置,可以根据传入的 `depts` 列表中的元素动态生成更新语句,将指定的 `deptId` 的 `ancestors` 值更新到 `sys_dept` 表中,并通过 `deptId` 的条件限制更新的范围。