Mybatis中foreach的使用

foreach一共有三种使用的场景,包括List、array和Map

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

 1、List类型的插入数据

<insert id="batchInsertClientDeviceList" parameterType="java.util.List" >
    INSERT INTO t_client_device_list (order_no,mac_id,client_code,status,order_time)
    <foreach collection="list" item="item" index="index" separator="union all">
         select #{item.orderNo, jdbcType=VARCHAR},#{item.macId, jdbcType=VARCHAR}
         from dual
    </foreach>
</insert>

2、List类型的查询

<select id="getClientDeviceList" parameterType="java.util.List" resultType="Device">
    select * from t_devices where id in
    <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</select>

3、参数Array类型查询

<select id="getClientDeviceList" parameterType="java.util.ArrayList" resultType="Device">
     select * from t_devices where id in
     <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
          #{item}
     </foreach>
</select>   

4、参数Map类型查询

map中存放了一个元素key为ids,value为List<String>用于id in的条件

<select id="getClientDeviceList" parameterType="java.util.HashMap" resultType="Device">
    select * from t_devices where mac like "%"#{mac}"%" and id in
    <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</select>

5、List类型的更新数据

<update id="updateOrderNum" parameterType="java.util.List">
	<foreach collection="list" item="id" index="index" separator=";"  open="begin" close=";end;">
		update sys_dict_type set order_num = #{index } where type_code = #{id}
	</foreach>
</update>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值