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鏈接,但是數據量太大效率不高。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM