foreach 的主要作用在构建 in 条件中,它可以在 sql 语句中进行迭代一个集合。foreach 元素的属性主要有 collection,item,separator,index,open,close。
<!--第一种-->
<select id="getList" resultType="com.epeit.api.model.Device">
SELECT *
FROM devcie
WHERE 1=1
<if test="ids != null and ids.size > 0">
AND id IN
<foreach collection="ids" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
</select>
<!--第二种-->
<select id="getList" resultType="com.epeit.api.model.Device">
SELECT *
FROM devcie
WHERE 1=1
<if test="ids != null and ids.size > 0">
AND
<foreach collection="ids" item="item" open="id IN(" separator="," close=")">
#{item}
</foreach>
</if>
</select>
<!--如果入参是一个逗号分隔的字符串比如"1,2,3,4",还可以简化写法,不用转成List,直接以字符串的形式传入即可-->
<select id="getList" resultType="com.epeit.api.model.Device">
SELECT *
FROM devcie
WHERE 1=1
<if test="strIds != null and strIds != ''">
AND id IN
<foreach collection="strIds.split(',')" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
</select>
<!--第一种-->
<update id="updateList">
<foreach collection="deviceList" item="item" separator=";">
UPDATE device
SET
name = #{item.name},
no = #{item.no}
WHERE
id = #{item.id}
</foreach>
</update>
<!--第二种-->
<update id="updateList">
UPDATE device
SET
del_flag = 1
WHERE 1=1
AND id IN
<foreach collection="ids" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</update>
<!--第一种-->
<insert id="insertList">
INSERT INTO
device
(id,name,no)
VALUES
<foreach collection="deviceList" item="item" separator=",">
( #{item.id}, #{item.name}, #{item.no} )
</foreach>
</insert>
<!--第二种-->
<insert id="insertList">
<foreach collection="deviceList" item="item" separator=";">
INSERT INTO
device
(id,name,no)
VALUES
( #{item.id}, #{item.name},#{item.no} )
</foreach>
</insert>