foreach 作用是对一个集合进行遍历 通常用在构建IN条件语句
一、foreach属性
item: 集合中每个元素迭代时的别名,在list和array中是其中的对象, 在map中是value。
index: 指的是迭代过程中 迭代到的位置。在list和array中index是元素的序号,在map中是元素的key。
open: foreach开始符号,常用在in(),values() 时。
close: foreach结束符号,同上。
collection: 主要分3种情况:
1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可
list对象默认用list作为键,array对象默认用array作为键,map没有默认的键 也可以使用@Param(“keyName”)来设置键。
二、使用实例
1.传入单参数List
// mapper接口
List<Role> getRolesByRoleIds(@Param("roleIds") List<Integer> roleIds);
// mapper sql 注意collection
<select id="getRolesByRoleIds" parameterType="java.util.List" resultMap="roleInfo">
SELECT role_id,role_name,valid FROM sys_role WHERE role_id IN
<foreach collection="roleIds" item="roleId" index="index" open="(" separator="," close=")">
#{roleId}
</foreach>
</select>
2.传入单参数array (类似于list)
3.传入多参数封装为map
// 多参数封装为map
Map ids = new HashMap<>();
ids.put("userId", userId);
ids.put("roleIds",roleIds);
this.roleOfUserMapper.addRoleOfUserByIds(ids);
// mapper 接口
int addRoleOfUserByIds(Map ids);
// mybatis sql
<insert id="addRoleOfUserByIds" parameterType="java.util.HashMap">
<selectKey keyProperty="serialNo" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT into sys_role_of_user(user_id, role_id, priority, start_date) VALUES
<foreach collection="roleIds" item="roleId" separator=",">
(#{userId},#{roleId},0,now())
</foreach>
</insert>