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

参数解释:
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="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>
  • 15
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值