Mybatis动态SQL之foreeach

Mybatis动态SQL之foreeach

八月 19, 2019

foreach元素:

特点:循环遍历集合,支持数组和List、Set接口,对其提供遍历功能
collection:迭代循环数组的名称
item:当前迭代的对象
index:当前迭代的索引
open和close:总个循环内容开头和结尾的字符串
separator:每次循环的分隔符

1
public List<Person> getPersonsByIds(int[] ids);
1
2
3
4
5
6
<select id="getPersonsByIds" resultType="person">
select * from person where id in
<foreach collection="array" item="id" index="i" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
1
2
3
4
5
SqlSession sqlSession = this.getSqlSessionFactory().openSession();

PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

Person person=personMapper.getPersonByCollection(new int[]{1,2,3,4,5});