一、前言
foreach 就是遍历迭代,在SQL中通常用在 in 这个关键词的后面。
foreach元素的属性主要有 item,index,collection,open,separator,close这6种
<foreach collection="" close="" index="" item="" open="" separator=""> .... </foreach>
- item:表示集合中每一个元素进行迭代时的别名,
- index:用于表示在迭代过程中,每次迭代到的位置,
- open:表示该语句以什么开始,
- separator:表示在每次进行迭代之间以什么符号作为分隔 符,
- close:表示以什么结束
这时候传入的参数就有这几种可能:list,array,map,下面我们分别对这三种情况进行代码案例说明。
二、案例
①当传入参数为List的时候
修改EmpMapper文件,增加findEmpsByList方法
/** * 集合传入 * @param ids * @return */ public List<Emp> findEmpsByList(List<Integer> ids);
修改EmpMapper.xml文件
<select id="findEmpsByList" resultType="com.queen.mybatis.bean.Emp"> select id,emp_name empName,emp_email empEmail, dept_id deptId from t_emp where id in <foreach collection="list" item="item_id" open="(" separator="," close=")"> #{item_id} </foreach> </select>
②当传入参数为Array的时候
修改EmpMapper文件,增加findEmpsByArray方法
/** * 数组传入 * @param ids * @return */ public List<Emp> findEmpsByArray(Integer[] ids);
修改EmpMapper.xml文件
<select id="findEmpsByArray" resultType="com.queen.mybatis.bean.Emp"> select id,emp_name empName,emp_email empEmail, dept_id deptId from t_emp where id in <foreach collection="array" item="item_id" open="(" separator="," close=")"> #{item_id} </foreach> </select>
③当传入参数为Map的时候
修改EmpMapper文件,增加findEmpsByMap方法
/** * Map传入 * @param ids * @return */ public List<Emp> findEmpsByMap(Map<String, Object> ids);
修改EmpMapper.xml文件
<select id="findEmpsByMap" resultType="com.queen.mybatis.bean.Emp"> select id,emp_name empName,emp_email empEmail, dept_id deptId from t_emp where id in <foreach collection="ids" item="item_id" open="(" separator="," close=")"> #{item_id} </foreach> </select>
使用map的时候需要注意:collection的值 “ids” 是存储在map中的key(比如:map.put(“ids”,ids));这个不是随便乱写的,需要特别注意;
=======欢迎大家拍砖,小手一抖,多多点赞哟!=======
版权声明:本文为博主原创文章,允许转载,但转载必须标明出处。