先上代码,先看下大概:
update tb_dm_shoping set uip='996' where userId in
<if test="list!=null and list.size()>0">
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
解析:
1、collection: 代表遍历的对象。属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合
2、separator:分隔符,自动在元素之间添加“,”
3、item:表示在迭代过程中每一个元素的别名,可以代表 List、Arry、Map中的value值
4、index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
5、open:开始符号
6、colse:结束符号
foreach的难点在用如何使用collection的值的问题,下面结合实际应用,我总结了一下,和大家做下分享
(1)当dao层传递参数是List<User>时,上述例子中的应改为:
dao层:
int updateById(List<User>)
mapper.xml:
<update id="updateById" parameterType="java.util.List">
update tb_dm_shoping set uip='996' where userId in
<if test="list!=null and list.size()>0">
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item.userId}
</foreach>
</if>
</update>
(2)当dao层传递参数为多个参数时:
dao层:
int updateById(@Param("userList")List<User>,@Param("uip")String uip)
mapper.xml:
<update id="updateById" parameterType="java.util.List">
update tb_dm_shoping set uip=#{uip} where userId in
<if test="list!=null and list.size()>0">
<foreach collection="userList" index="index" item="item" open="(" separator="," close=")">
#{item.userId}
</foreach>
</if>
</update>