mybatis的批量更新

说到批量操作,我觉得思路也就是两种:一种是for循环一条一条更新,一种执行一条sql批量更新。

我们在这里说一下sql执行批量更新,直接上代码。

 

<!-- 通过入参list进行循环组装sql进行批量更新 -->
    <update id="batchUpdate" parameterType="com.a.b.User">
        <!-- 循环着组装sql语句
             separator=";" 代表着每次循环完,在sql后面放一个分号
             item="item" 循环List的每条的结果集
             collection="list" list 即为传过来的参数User对象list -->
        <foreach collection="list" separator=";" item="item">
            update t_user set
            user_name = #{item.name},
            where id = #{item.id}
        </foreach>
    </update>

 

<!--case when更新-->
<update id="batchUpdate" parameterType="java.util.List">
    update department
    <trim prefix="set" suffixOverrides=",">
      <trim prefix="sort =case" suffix="end,">
        <foreach collection="list" item="item" index="index">
          <if test="item.id !=null and item.id != -1">
            when id=#{item.id} then #{item.sort}
          </if>
        </foreach>
      </trim>
    </trim>
    where id in
    <foreach collection="departments" index="index" item="item" separator="," open="(" close=")">
      #{item.id}
    </foreach>
  </update>

下面这种方式,一般都会搭配唯一索引使用,如果存在就更新该记录,如果不存在insert新的记录 

    <!--ON DUPLICATE KEY UPDATE-->	
    <insert id="updateBatch" parameterType="java.util.List">
        insert into t_user(id,name)VALUES
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.id,jdbcType=BIGINT},#{item.name,jdbcType=VARCHAR})
        </foreach>
        ON DUPLICATE KEY UPDATE
        id=VALUES(id),name = VALUES(name)
	</insert>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值