• 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链接,但是数据量太大效率不高。

  • 相关阅读:
    Golang gRPC 入门
    ProtoBuf编解码
    Proto3语法入门
    Golang RPC入门
    Windows用mstsc(远程桌面)远程Ubuntu 12.04时无法显示Ubuntu桌面解决办法
    ABAPSM30配置TCODE
    eclipselog4j.properties配置
    Hadoop—配置3个副本,但是实际只有1个副本。
    Hadoop—org.apache.hadoop.io.nativeio.NativeIO$Windows.access0
    Jmeter BeanShell使用场景
  • 原文地址:https://www.cnblogs.com/enchaolee/p/11362080.html
Copyright © 2020-2023  润新知