foreach 标签
foreach 标签主要用于构建 in 条件,可在 sql 中对集合进行迭代。也常用到批量删除、添加等操作中。
<!-- in查询所有,不分页 -->
<select id="selectIn" resultMap="BaseResultMap">
select name,hobby from student where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
-
collection:collection 属性的值有三个分别是 list、array、map 三种
-
item :表示在迭代过程中每一个元素的别名
-
index :表示在迭代过程中每次迭代到的位置(下标)
-
open :前缀
-
close :后缀
-
separator :分隔符,表示迭代时每个元素之间以什么分隔
参数
- 只有一个数组参数或集合参数
- 当参数类型为集合的时候,默认会转换为map类型,并添加一个key为collection的值
- 如果参数类型是List集合,那么就继续添加一个key为list的值 -
- 当参数类型为数组的时候,也会转成map类型,默认的key为array
- 有多个参数
- 当有多个参数的时候,要使用@Param注解给每个参数指定一个名字,否则在SQL中使用参数时就会不方便。因此将collection设置为@Param注解指定的名字
- 参数时Map类型
- 使用Map和使用@Param注解方式类似,将collection指定为对应Map中的key即可 -
- 如果要循环所传入的Map,推荐使用@Param注解指定名字,此时可将collection设置为指定的名字
- 如果不想指定名字,就使用默认值_parameter
批量查询
<select id="selectByIdList" resultMap="userMap">
select
<include refid="userSql" />
from sys_user
<where>
id in
<foreach collection="list" open="(" close=")" separator=","
item="id" index="i">
#{id}
</foreach>
</where>
</select>
批量更新
/**
* 使用foreach批量更新
* @param map
*/
void updateByMap(Map<String,Object> map);
<update id="updateByMap">
update sys_user
<set>
<foreach collection="_parameter" item="val" index="key" separator=",">
${key} = #{val}
</foreach>
</set>
where id=#{id}
</update>
批量模糊匹配
<!-- 利用foreach根据多个品牌名字分类,模糊搜索数据 -->
<select id="listGoodBrand" resultMap="goodsMap">
SELECT id,name,type FROM goods_brand WHERE delete_flag=0 and
<foreach collection="goodList" item="item" index="index" open="(" separator="or" close=")">
name LIKE CONCAT('%',#{item},'%')
</foreach>
order by id desc
</select>
separator=“or” 这个属性拼接 sql
批量插入
<!-- 批量插入-->
<insert id="batchSave">
INSERT INTO dhz_role_menu(role_id,menu_id,create_time)
values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.roleId},#{item.menuId},now())
</foreach>
</insert>