Mybatis动态SQL中如何使用foreach标签遍历集合呢?
下文笔者讲述mybatis中foreach标签的使用简介说明,如下所示
foreach简介
foreach是mybatis中用于遍历的关键字
有item、index、collection、open、separator、close六种属性可使用
例
<foreach collection="" close="" index="" item="" open="" separator=""> ... </foreach>
标签属性
item:表示集合中的每一个元素进行迭代时的别名 index:用于表示在迭代的过程中,每次迭代到的位置 open:表示该语句以什么开始 separator:表示在每次迭代之间以什么符号作为分隔符 close:表示以什么结束
1.传入list列表参数
修改mapper.class的接口类文件,增加findStudentByList方法:
/**
*传入列表
*
*/
public List<Student> findStudentByList(List<Integer> ids);
说明:以List且泛型为Student实体类来接收查询结果,入参为ids,多个Integer型id组成的列表。
修改StudentMapper.xml文件,写对应方法的动态SQL:
<select id "findStudentByList" parameterType="Integer" resultType="com.ali.entity.Student">
select id,st_name,st_age from t_student where id in
<foreach collection="list" item="item_id" open"(" separator="," close=")">
#{item_id}
</foreach>
</select>
说明:
select标签
id为对应mapper接口类里面的方法名
resultType对应结果类型的entity类
foreach标签中的属性定义说明:
传入集合类型为列表
每一个元素迭代时的别名为item_id
语句以“(”开始,每次进行迭代之间以“,”作为分隔符,并以“)”为结束
2.传入array数组参数
修改mapper.class的接口类文件,增加findStudentByArray方法:
/**
*传入数组
*
*/
public List<Student> findStudentByArray(Integer[] ids);
说明:入参类型为Integer类型数组对象ids
返回类型为Student泛型的列表
修改StudentMapper.xml文件,写对应方法的动态SQL:
<select id="findStudentByArray" parameterType="Integer" resultType="com.ali.entity.Student">
select id,st_name,st_age from t_student where id in
<foreach collection="array" item="item_id" open"(" separator="," close=")">
#{item_id}
</foreach>
</select>
说明:select标签
id为对应mapper接口类里面的方法名
resultType对应结果类型的entity类
foreach标签中的属性定义说明:
传入集合类型为列表,
每一个元素迭代时的别名为item_id,
该语句以“(”开始,每次进行迭代之间以“,”作为分隔符,并以“)”为结束
3.传入hash哈希参数
修改mapper.class的接口类文件,增加findStudentByMap方法:
/**
*传入哈希
*
*/
public List<Map> findStudentByMap(Map<String,Object> ids);
说明: mapper的接口文件,入参:键为String值为Object的Map类型的对象ids
修改对应mapper.xml文件:
<select id="findStudentByMap" parameterType="Map" resultType="com.ali.entity.Student">
select id,st_name,st_age from t_student 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)这个键的字符串不是随便写的,是对应的)
说明:
select标签,
id为对应mapper接口类里面的方法名,
resultType对应结果类型的entity类,
foreach标签中的属性定义说明:
传入集合类型为列表,
每一个元素迭代时的别名为item_id,
该语句以“(”开始,每次进行迭代之间以“,”作为分隔符,并以“)”为结束
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


