mybatis动态sql中foreach的使用之-----List传单个和多个参数

本文详细解析了MyBatis框架中foreach元素的使用方法,包括collection、separator、item、index、open和close等属性的含义及应用场景。通过具体示例展示了如何在mapper.xml文件中使用foreach进行List和Map类型的参数传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先上代码,先看下大概:

update tb_dm_shoping set uip='996' where userId in 
<if test="list!=null and list.size()>0">
    <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</if>

解析:

1、collection: 代表遍历的对象。属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合

2、separator:分隔符,自动在元素之间添加“,”

3、item:表示在迭代过程中每一个元素的别名,可以代表 List、Arry、Map中的value值

4、index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选

5、open:开始符号

6、colse:结束符号

foreach的难点在用如何使用collection的值的问题,下面结合实际应用,我总结了一下,和大家做下分享

(1)当dao层传递参数是List<User>时,上述例子中的应改为:

dao层:
int updateById(List<User>)

mapper.xml:
<update id="updateById" parameterType="java.util.List">
  update tb_dm_shoping set uip='996' where userId in
   <if test="list!=null and list.size()>0">
     <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{item.userId}
    </foreach>
   </if>
</update>

(2)当dao层传递参数为多个参数时:

dao层:
int updateById(@Param("userList")List<User>,@Param("uip")String uip)

mapper.xml:
<update id="updateById" parameterType="java.util.List">
  update tb_dm_shoping set uip=#{uip} where userId in
   <if test="list!=null and list.size()>0">
     <foreach collection="userList" index="index" item="item" open="(" separator="," close=")">
        #{item.userId}
    </foreach>
   </if>
</update>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值