mybatis batch update strategy

 We know db cycle operation will lead to the number of connections is full, serious impact on database performance. So when db be DQL and DML, according to business logic as far as possible batch operation, where we introduce the next batch update mysql use mybatis of two ways.

 

method one:

 

<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>

 

But Mybatis mapping file sql statement is not supported by default ";" at the end, which is not supported execute multiple sql statement. Url is required in connection mysql plus & allowMultiQueries = true can perform this.

Second way:

 <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>

   Which is when ... then ... sql in the "switch" syntax. Here With mybatis of <foreach> syntax to piece together sql became batch updates, this approach does not require modification mysql link, but the amount of data is too inefficient.

 

Guess you like

Origin www.cnblogs.com/enchaolee/p/11362080.html