zoukankan      html  css  js  c++  java
  • mybatis批量更新策略

      我们知道循环中操作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链接,但是数据量太大效率不高。

  • 相关阅读:
    Java类型转换
    Java数据类型
    Java运行机制-简单理解
    Dos基础命令
    MarkDown
    MSP430 ADC12模块(转)
    解决拷贝中文注释到KEIL4.6中呈现乱码的问题
    ADS1.2 DEBUG调试时提示:erro starting external process,Process error code 87(0x57)
    MDK4.6提示不能找到库
    在JLINK4.12的安装目录下没有LPC2214.jflash文件的解决办法
  • 原文地址:https://www.cnblogs.com/enchaolee/p/11362080.html
Copyright © 2011-2022 走看看