Mybatis的foreach的批量操作

104 阅读1分钟

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

image.png 1.查询的时候: select , {colstr} from {tableName} where del_flag = 0 and id_bp_step = #{idBpStep} and id in #{id} order by id SELECT * FROM devcie WHERE 1=1 AND id IN #{item}

<!--第二种-->
<select id="getList" resultType="com.xs.sql.My"> 
  	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.xs.sql.My">
	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>

2.批量更新的时候

<!--第一种-->
<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>
<!--第三种-->
update ${tableName} set DEL_FLAG = 1, deleteor = #{deleteor} where id in #{id}

3.批量插入的时候

<!--第一种-->
<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>
insert ignore into ${tableName} (AIP_ID, BOX_ID) values (#{id}, #{boxId})

原文链接:blog.csdn.net/m0_61916154…