MyBatis<foreach>标签的用法及多种循环方式

时间:2025-04-26 08:18:21

参数解释:
foreach 的主要作用在构建 in 条件中,它可以在 sql 语句中进行迭代一个集合。foreach 元素的属性主要有 collection,item,separator,index,open,close。

属性 描述
collection 指定要遍历的集合。表示传入过来的参数的数据类型。该属性是必须指定的,要做 foreach 的对象。
index 索引,index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置。遍历 list 的时候 index 就是索引,遍历 map 的时候 index 表示的就是 map 的 key,item 就是 map 的值。
item 表示本次迭代获取的元素,若collection为List、Set或者数组,则表示其中的元素;若collection为map,则代表key-value的value,该参数为必选
open 表示该语句以什么开始,最常用的是左括弧’(’,注意:mybatis会将该字符拼接到整体的sql语句之前,并且只拼接一次,该参数为可选项
separator 表示在每次进行迭代之间以什么符号作为分隔符。select * from tab where id in(1,2,3)相当于1,2,3之间的","
close 表示该语句以什么结束,最常用的是右括弧’)’,注意:mybatis会将该字符拼接到整体的sql语句之后,该参数为可选项
查询
	<!--第一种-->
	<select id="getList" resultType=""> 
	  	SELECT *
	  	FROM devcie 
	 	WHERE 1=1 
	 	 <if test="ids != null and  > 0"> 
	   		AND id IN
	   		<foreach collection="ids" item="item" open="(" separator="," close=")"> 
	   		 #{item} 
	  		 </foreach> 
	  	 </if> 
	 </select>
 
	<!--第二种-->
	<select id="getList" resultType=""> 
	  	SELECT *
	  	FROM devcie 
	  	WHERE 1=1 
	  	<if test="ids != null and  > 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="">
		SELECT *
	  	FROM devcie 
	 	WHERE 1=1 
	 	 <if test="strIds != null and strIds != ''"> 
	   		AND id IN
	   		<foreach collection="(',')" item="item" open="(" separator="," close=")"> 
	   		 #{item} 
	  		 </foreach> 
	  	 </if>
	</select>

批量更新

	<!--第一种-->
	<update id="updateList">
		<foreach collection="deviceList" item="item"  separator=";">
		    UPDATE device 
		    SET 
		       name = #{},
		       no = #{}
		    WHERE  
		       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=",">
            ( #{}, #{}, #{} )
        </foreach>
    </insert>

	<!--第二种-->
    <insert id="insertList">
    	<foreach collection="deviceList" item="item" separator=";">
        INSERT INTO
       	device
        	(id,name,no)
        VALUES
            ( #{}, #{},#{} )
        </foreach>
    </insert>