其实这三种集合类型在<foreach>时大致可以分为两类,list和set为一类,map为一类
先介绍下啊<foreach>的几个参数
1. collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类 型为:List、数组、map 集合。
2. item :循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details,在3. list和数组中是其中的对象,在map中是value。
4. index :在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
5. open :表示该语句以什么开始
6. close :表示该语句以什么结束
7. separator :表示元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
list,set
先看代码
mapper接口:
@Mapper
public interface ConstitutionDao {
List<Integer> getConstitutionIdByConstitutionType(@Param("set") Set<Character> type);
}
mapper.xml文件
<select id="getConstitutionIdByConstitutionType" resultType="java.lang.Integer">
select constitutionId from constitutions
where constitutionType in(
<foreach collection="set" item="type" separator=",">
#{type}
</foreach>
)
</select>
注意:
- 在循环遍历list和set时如果入参有@Param注解,则collection属性必须为注解里的值;如果没有@Param注解list对应的collection为"list",set对应的为"set"
- item属性可以随便写,但是下方#{}必须与其保持一致,item属性代指的是每次循环遍历出的集合中的元素。上面例子中元素是Character类型的,如果是对象类型,还可以通过" item值.属性名"来访问对象的属性
map
mapper接口:
@Mapper
public interface UserConstitutionsDao {
int UserConstitutionsInsert(
@Param("uid")
long uid,
@Param("map")
Map<Character, Double> occupancy);
}
mapper.xml:
<insert id="UserConstitutionsInsert" >
insert into user_constitutions(userId,constitutionType,percent) values
<foreach collection="map" separator="," item="value" index="key">
(#{uid},#{key},#{value})
</foreach>
</insert>
注意:
在遍历map集合时,index属性一定代指的是map中的key,item属性一定代指的是map中的value。index和item的属性值可以随便取,但是必须通过#{key属性名},#{item属性名}来访问key和value