foreach的使用

本文详细介绍了MyBatis中的foreach元素,主要用在构建SQL的IN条件中,如示例所示,用于遍历集合并生成SQL语句。文章通过解析foreach的属性(item、index、collection、open、separator、close)来说明其工作原理,并给出在更新和查询操作中的实际应用案例。强调了在处理数组参数时使用foreach的优越性,以避免在业务层进行多次数据库访问。
摘要由CSDN通过智能技术生成

mybatis foreach的使用

*foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。*

**foreach元素的属性主要有 item,index,collection,open,separator,close。**

​ ~item表示集合中每一个元素进行迭代时的别名
​ ~index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,
​ ~open表示该语句以什么开始,
​ ~separator表示在每次进行迭代之间以什么符号作为分隔 符,
​ ~close表示以什么结束。

select
        a.type,
        b.*,
        o.id 'oid',
        o.order_sn 'orderSn',
        o.add_time 'addTime',
        o.order_status 'orderStatus',
        a.start_time 'startTime',
        a.delivery_time 'deliveryTime',
        a.end_time 'endTime',
        o.actual_price 'actualPrice'
        from dts_brand b
		left join dts_order_goods og on og.brand_id = b.id
		left join dts_order o on o.id = og.order_id
		left join dts_order_additional a on a.order_id = o.id
		WHERE o.deleted = 0 and o.user_id = #{userId}
		<if test="orderType!=null and orderType!=''">
          and o.order_status in
          <foreach collection="orderType" item="orderItem" open="(" separator="," close=")">
            #{orderItem}
          </foreach>
        </if>
		group by o.id
		order by o.add_time desc

参数为数组时,尽量使用foreach,不要在业务层循环(频繁访问数据库)

<update id="updateGoods">
	update dts_goods set is_on_sale = 0,update_time=now()
	where id in(
		<foreach collection="ids" item="id" separator=",">
			#{id}
		</foreach>
	)
</update>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值