1. 基本用法
- collection属性:要遍历的集合
- item属性:遍历集合的过程中能得到每一个具体对象,在item属性中设置一个名字,将来通过这个名字引用遍历出来的对象
- separator属性:指定当foreach标签的标签体重复拼接字符串时,各个标签体字符串之间的分隔符,如果是最后一次,不会追加
- open属性:指定整个循环把字符串拼好后,字符串整体的前面要添加的字符串
- close属性:指定整个循环把字符串拼好后,字符串整体的后面要添加的字符串
- index属性:这里起一个名字,便于后面引用
- 遍历List集合,这里能够得到List集合的索引值
- 遍历Map集合,这里能够得到Map集合的key
<foreach collection="empList" item="emp" separator="," open="values" index="myIndex">
<!-- 在foreach标签内部如果需要引用遍历得到的具体的一个对象,需要使用item属性声明的名称 -->
(#{emp.empName},#{myIndex},#{emp.empSalary},#{emp.empGender})
</foreach>
2. 批量查询举例
传入一个id列表,根据每一个id的值去查询具体信息
<select id="queryBatch" resultType="employee">
select * from t_emp
where emp_id in
<!-- 遍历的数据
( 1 , 2 , 3 )
-->
<foreach collection="ids" open="(" separator="," close=")" item="id">
<!-- 遍历的内容, #{遍历项 item指定的key}-->
#{id}
</foreach>
</select>
3. 批量删除举例
传入一个id列表,根据每一个id的值去删除信息
<delete id="deleteBatch">
delete from t_emp where id in
<foreach collection="ids" open="(" separator="," close=")" item="id">
#{id}
</foreach>
</delete>
4. 批量插入举例
<insert id="insertBatch">
insert into t_emp (emp_name,emp_salary)
values
<foreach collection="list" separator="," item="employee">
(#{employee.empName}, #{employee.empSalary})
</foreach>
</insert>
5. 批量修改举例
<update id="updateBatch">
<foreach collection="list" item="emp">
update t_emp set emp_name = #{emp.empName} , emp_salary = #{emp.empSalary}
where emp_id = #{emp.empId} ;
</foreach>
</update>
6. 总结
- 例如修改语句,我们找不到需要循环的sql片段,那就可以把整个sql语句循环。
- 如果一个标签涉及多个语句! 需要设置允许指定多语句 !在数据库连接信息的URL地址中设置: allowMultiQueries=true
- 如果没有给接口中List类型的参数使用@Param注解指定一个具体的名字,那么在collection属性中默认可以使用collection或list来引用这个list集合。