一、简介
foreach用来实现循环,一共有三种类型,分别为List,array,map三种
二、属性介绍
collection:输入对象中的集合属性。作为入参时,List<?>对象默认用list替代作为键,数组对象有array作为键,Map对象没有默认的键;通俗点说就是collection类型为集合时,值为:list,collection类型为数组时,值为array,collection类型为Map时,没有默认值。
如何修改这个默认值呢?在mapper.java文件的方法对应的参数前添加:@Param(value="你的命名") 即可。这样collection的值即为你此处设置的值。
item:循环体中的具体对象。其值可为任意值。支持属性的点路径访问,如item.age。在list和array中是具体的对象,在map中是value。
open:foreach代码的开始符号,一般是“(”
close:foreach代码的关闭符号,一般是")"
separator:元素之间的分隔符。
index:在list和array中,index是元素的符号,在map中,index是元素的key。
三、示例
1.单表更新多条数据(collection用默认值)
1)mapper.xml
<insert id="list" parameterType="cn.itcast.ssm.po.Items">
INSERT INTO MY_ITEMS
(<include refid="Base_Column_List"></include>)
<foreach collection="otherName" item="item" separator="union all">
SELECT
#{item.id},
#{item.name},
#{item.price}
FROM dual
</foreach>
</insert>
2)mapper.java
public interface ItemsMapper {
int insertList(List<Items> list);
}
service和controller层就不写了
2.单表更新多条数据(collection用自定义值)
1)mapper.xml
<insert id="insertList" parameterType="cn.itcast.ssm.po.Items">
INSERT INTO MY_ITEMS
(<include refid="Base_Column_List"></include>)
<foreach collection="otherName" item="item" separator="union all">
SELECT
#{item.id},
#{item.name},
#{item.price}
FROM dual
</foreach>
</insert>
2)mapper.java
public interface ItemsMapper {
int insertList(@Param(value="otherName") List<Items> list);
}
3.查询多条
<select id="selectList" parameterType="cn.itcast.ssm.po.Items"
resultMap="BaseResultMap">
select * from MY_ITEMS
<if test="list!=null">
<where>
<foreach collection="list" item="user_id" open="and ("
close=")" separator="or">
id=#{user_id}
</foreach>
</where>
</if>
</select>
四、oracle一次插入多条数据的sql语句
INSERT INTO MY_ITEMS(id,name,price)
SELECT '11', '12', 13 FROM dual union all SELECT '12', '12', 13 FROM dual union all SELECT '13', '12', 13 FROM dual
INSERT INTO MY_ITEMS(id,name,price)
(SELECT '11', '12', 13 FROM dual union all SELECT '12', '12', 13 FROM dual union all SELECT '13', '12', 13 FROM dual)
collection:
1.单表更新多条数据(collection用默认值)