mybatis 的 foreach语句批量操作

foreach

  • 介绍
  - collection:必填,值为要迭代循环的属性名。这个属性值的情况有很多
  - item :变量名,值为从迭代对象中取出来的每一个值
  - index: 索引的属性名,在集合数组情况下值为当前索引值,当迭代循环的对象时Map类型时,这个值为map的key值
  - open: 整个循环内容开头的字符串
  - close:整个循环内容结尾的字符串
  - separator: 每次循环的分隔符
  • 参数
  - 只有一个数组参数或集合参数

    - 当参数类型为集合的时候,默认会转换为map类型,并添加一个key为collection的值
    - 如果参数类型是List集合,那么就继续添加一个key为list的值
    - 当参数类型为数组的时候,也会转成map类型,默认的key为array

  - 有多个参数
    - 当有多个参数的时候,要使用@Param注解给每个参数指定一个名字,否则在SQL中使用参数时就会不方便。因此将collection设置为@Param注解指定的名字
  
  - 参数时Map类型
    - 使用Map和使用@Param注解方式类似,将collection指定为对应Map中的key即可
    - 如果要循环所传入的Map,推荐使用@Param注解指定名字,此时可将collection设置为指定的名字
    - 如果不想指定名字,就使用默认值_parameter
  • 增加
void saveUserRole(@Param("userSn") Long userSn, @Param("list") List<Long> list);
<insert id="saveUserRole">
        insert into tb_user_role
        (user_sn,role_sn)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{userSn},#{item})
        </foreach>
</insert>

<insert id="insertList" useGeneratedKeys="true" keyProperty="id">
  insert into sys_user
  (user_name,user_password,user_email,user_info,head_img,create_time)
  values
  <foreach collection="list" item="user" separator=",">
   (
   #{user.userName},#{user.userPassword},#{user.userEmail},
   #{user.userInfo},#{user.headImg,jdbcType=BLOB},
   #{user.createTime,jdbcType=TIMESTAMP}
   )
  </foreach>
</insert>

  • 批量查询
 <select id="selectByIdList" resultMap="userMap">
  select
  <include refid="userSql" />
  from sys_user
  <where>
   id in
   <foreach collection="list" open="(" close=")" separator=","
    item="id" index="i">
    #{id}
   </foreach>
  </where>
 </select>

  • 批量更新
 /**
  * 使用foreach批量更新
  * @param map
  */
 void updateByMap(Map<String,Object> map);
 <update id="updateByMap">
  update sys_user
  <set>
   <foreach collection="_parameter" item="val" index="key" separator=",">
    ${key} = #{val}
   </foreach>
  </set>
  where id=#{id}
 </update>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值