手机版
你好,游客 登录 注册
背景:
阅读新闻

mybatis批量更新策略

[日期:2019-08-21] 来源:cnblogs.com/enchaolee  作者:梦飞翔up [字体: ]

我们知道循环中操作db会导致连接数满,严重影响数据库性能。所以在对db进行DQL与DML时,根据业务逻辑尽量批量操作,这里我们介绍下使用mybatis批量更新mysql的两种方式。

方式一:

<update id="updateBatch"  parameterType="Java.util.List"> 
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update tableName
        <set>
            name=${item.name},
            name2=${item.name2}
        </set>
        where id = ${item.id}
    </foreach>     
</update>

但Mybatis映射文件中的sql语句默认是不支持以" ; " 结尾的,也就是不支持多条sql语句的执行。所以需要在连接mysql的url上加 &allowMultiQueries=true 这个才可以执行。

方式二:

<update id="updateBatch" parameterType="java.util.List">
      update
      <include refid="tableName"/>
      <trim prefix="set" suffixOverrides=",">
          <trim prefix="update_acc =case" suffix="end,">
              <foreach collection="list" item="item">
                  <if test="item.updateAcc!=null">
                      when clue_id=#{item.clueId} then #{item.updateAcc}
                  </if>
              </foreach>
          </trim>
          <trim prefix="update_time =case" suffix="end,">
              <foreach collection="list" item="item">
                  <if test="item.updateTime!=null">
                      when clue_id=#{item.clueId} then #{item.updateTime}
                  </if>
              </foreach>
          </trim>
      </trim>
      <where>
          <foreach collection="list" separator="or" item="item">
              (org_id = #{item.orgId}
              and clue_id = #{item.clueId})
          </foreach>
      </where>
  </update>

其中when...then...是sql中的"switch" 语法。这里借助mybatis的<foreach>语法来拼凑成了批量更新的sql,这种方式不需要修改mysql链接,但是数据量太大效率不高。

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

本文永久更新链接地址https://www.linuxidc.com/Linux/2019-08/160249.htm

linux
相关资讯       MyBatis  mybatis批量更新 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款