collection:
需做foreach的对象,作为入参时,list、array对象时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“paramName”)注解来设置自定义collection属性值,设置keyName后,list、array会失效;
item: 集合元素迭代时的别名称,该参数为必选项
index:map中代指key,其它时用于表示在迭代过程中,每次迭代到的位置
separator:元素间的分隔符
open:遍历集合开始时使用
close:遍历集合结束时使用
1、collection为list时:
- <resultMap id="BaseResultMap" type="com.list.demo">
- <result column="id" property="id"/>
- <result column="name" property="name"/>
- <result column="age" property="age"/>
- <result column="gender" property="gender"/>
- <result column="address" property="address"/>
- resultMap>
-
- <select id="selectTestList1" resultMap="BaseResultMap">
- SELECT id, name, age, gender, address
- FROM test_01
- WHERE
- id in
- <foreach collection="ids" item="id" separator="," open="(" close=")">
- #{id}
- foreach>
- select>
对应的Mapper接口为:List
2、collection为array时:
- <select id="selectTestList2" resultMap="BaseResultMap">
- SELECT id, name, age, gender, address
- FROM test_01
- WHERE
- name in
- <foreach collection="names" item="name" separator="," open="(" close=")">
- #{name}
- foreach>
- select>
对应的Mapper接口为:List
3、collection为map时:
- <select id="selectTestList3" resultMap="BaseResultMap">
- SELECT id, name, age, gender, address
- FROM test_01
- WHERE
- (name, age) in
- <foreach collection="maps" item="v" index="k" separator="," open="(" close=")">
- (#{k}, #{v})
- foreach>
- select>
对应的Mapper接口为:List
特别注意:当collection为list或array时,index代表的是当前序号
比如:
- <foreach collection="list" item="item" index="i">
- <if test="i > 0">
- ${item[i-1]}=#{item}
- if>
- foreach>
注意:用index时要用$而不是#