foreach
- collection:必填,值为要迭代循环的属性名。这个属性值的情况有很多
- item :变量名,值为从迭代对象中取出来的每一个值
- index: 索引的属性名,在集合数组情况下值为当前索引值,当迭代循环的对象时Map类型时,这个值为map的key值
- open: 整个循环内容开头的字符串
- close:整个循环内容结尾的字符串
- separator: 每次循环的分隔符
- 只有一个数组参数或集合参数
- 当参数类型为集合的时候,默认会转换为map类型,并添加一个key为collection的值
- 如果参数类型是List集合,那么就继续添加一个key为list的值
- 当参数类型为数组的时候,也会转成map类型,默认的key为array
- 有多个参数
- 当有多个参数的时候,要使用@Param注解给每个参数指定一个名字,否则在SQL中使用参数时就会不方便。因此将collection设置为@Param注解指定的名字
- 参数时Map类型
- 使用Map和使用@Param注解方式类似,将collection指定为对应Map中的key即可
- 如果要循环所传入的Map,推荐使用@Param注解指定名字,此时可将collection设置为指定的名字
- 如果不想指定名字,就使用默认值_parameter
void saveUserRole ( @Param ( "userSn" ) Long userSn, @Param ( "list" ) List< Long> list) ;
< insert id = " saveUserRole" >
insert into tb_user_role
(user_sn,role_sn)
values
< foreach collection = " list" item = " item" index = " index" separator = " ," >
(#{userSn},#{item})
</ foreach>
</ insert>
< insert id = " insertList" useGeneratedKeys = " true" keyProperty = " id" >
insert into sys_user
(user_name,user_password,user_email,user_info,head_img,create_time)
values
< foreach collection = " list" item = " user" separator = " ," >
(
#{user.userName},#{user.userPassword},#{user.userEmail},
#{user.userInfo},#{user.headImg,jdbcType=BLOB},
#{user.createTime,jdbcType=TIMESTAMP}
)
</ foreach>
</ insert>
< select id = " selectByIdList" resultMap = " userMap" >
select
< include refid = " userSql" />
from sys_user
< where>
id in
< foreach collection = " list" open = " (" close = " )" separator = " ,"
item = " id" index = " i" >
#{id}
</ foreach>
</ where>
</ select>
void updateByMap ( Map< String, Object> map) ;
< update id = " updateByMap" >
update sys_user
< set>
< foreach collection = " _parameter" item = " val" index = " key" separator = " ," >
${key} = #{val}
</ foreach>
</ set>
where id=#{id}
</ update>