mybatis foreach标签使用

177 阅读1分钟

本文已参与「新人创作礼」活动, 一起开启掘金创作之路。

foreach 标签 主要用于循环迭代

<foreach collection="" item="" open="" close="" separator="" index="">
</foreach>
foreach 对一个数组或集合进行遍历
collection:指定要遍历的集合或数组
item:设置别名
close:设置循环体的结束内容
open:设置循环体的开始内容
separator:设置每一次循环之间的分隔符
index:若遍历的是list,index代表下标;若遍历的是mapindex代表键

 `collection:要迭代的集合(数组)【list类型的参数会特殊处理封装在map中,map的key就叫list】
 ``item:将当前遍历出的元素赋值给指定的变量``      
 ``open:遍历出所有结果拼接一个开始的字符``      
 ``close:遍历出所有结果拼接一个结束的字符``      
 ``separator:元素与元素之间的分隔符``      
 ``index:索引``           
 ``迭代的是 List 集合:index 表示的是当前元素的下标,item就是当前值;``   
 ``迭代的是 Map 集合:index 表示的当前元素的 key,item就是map的值`` 
 ``#{变量名}就能取出变量的值也就是当前遍历出的元素` |

## 使用 foreach 标签

  在接口中声明方法:

//查询员工 id在给定集合中
public List<Employee> getEmpsByConditionForEach(@Param("ids")List<Integer> ids);
  在对应的 xml 中进行配置:

[![复制代码](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d268cd1bd80a4f07b6379595d52507be~tplv-k3u1fbpfcp-zoom-1.image)](<> "复制代码")

<!--
    public List<Employee> getEmpsByConditionForEach(List<Integer> ids);
-->
<!--
    collection:指定要遍历的集合
        list 类型的参数会特殊处理封装在 map中,map的key就叫 list
    item:将当前遍历出的元素赋值给指定的变量
    separator:每个元素之间的分隔符
    open:遍历出所有结果拼接一个开始的字符
    close:遍历出所有的结果拼接一个结束的字符
    index:索引。遍历list的时候index是索引,item就是当前值;
                遍历map的时候index表示的就是map的key,item就是map的值

    #{变量名} 就能取出变量的值也就是当前遍历出的元素

-->
<select id="getEmpsByConditionForEach" resultType="Employee">
    select * from tbl_employee
    <!--
        <foreach collection="list" item="item_id" separator="," open="(" close=")" index="i">
            #{item_id}
        </foreach>
    -->
    <foreach collection="ids" item="item_id" separator="," open="where id in (" close=")" index="i">
        #{item_id}
    </foreach>
</select>

  **注意**:

  (1)如果传递的参数在 List/Collection/Array 中,MyBatis 还是会将 list,、collection、array 放在 map 中,List 集合会以 list 为键,Array 为已 array 为键。

  (2)可以在方法的形参处使用 @Param(key) 来为 map 指定键。

| 12 | `//通过list集合实现批量删除``public` `void`  `deleteMoreByList(``@Param``(``"ids"``)List<Integer> ids);` |