05_Mybatis的批量更新與插入

@Author Jacky Wang
在使用Mybatis進(jìn)行批量插入與更新的時(shí)候,遍歷一條條的操作效率太低,因此采用mybatis的動(dòng)態(tài)sql實(shí)現(xiàn)批量操作。

1. mybatis批量插入

示例如下:

這里有個(gè)注意點(diǎn):
    括號(hào)的分隔不能在<foreach>標(biāo)簽里面使用close與open使用。

<insert id="batchAddTagBindingRecord" parameterType="java.util.List" useGeneratedKeys="true">
    insert t_tag_binding (goods_id,status,epc,tid,op_scene,origin_id,create_date,creater,client_id)values
    <foreach collection="list" item="item" index="index" separator=",">
        ( #{item.goodsId,jdbcType=BIGINT},
        #{item.status,jdbcType=VARCHAR},
        #{item.epc,jdbcType=VARCHAR},#{item.tid,jdbcType=VARCHAR},
        #{item.opScene,jdbcType=VARCHAR},#{item.originId,jdbcType=BIGINT},
        #{item.createDate,jdbcType=TIMESTAMP},#{item.creater,jdbcType=BIGINT}, #{item.clientId,jdbcType=BIGINT}
        )
    </foreach>
</insert>

2. mybatis批量更新

示例如下:

MySQL沒有提供直接的方法來實(shí)現(xiàn)批量更新,但可以使用case when語法來實(shí)現(xiàn)這個(gè)功能。
注意:最外層trim不能包where條件

<update id="batchUpdateTagStatus" parameterType="java.util.List">
    update t_tag
    <trim prefix="set" suffixOverrides=",">
        <trim prefix="goods_id = case" suffix="end,">
            <foreach collection="list" item="item" index="index">
                when epc=#{item.epc} then #{item.goodsId}
            </foreach>
        </trim>
        <trim prefix="status = case" suffix="end,">
            <foreach collection="list" item="item" index="index">
                <if test="item.status!=null">
                    when epc=#{item.epc} then #{item.status}
                </if>
            </foreach>
        </trim>
        <trim prefix="last_update = case" suffix="end,">
            <foreach collection="list" item="item" index="index">
                <if test="item.lastUpdate!=null">
                    when epc=#{item.epc} then #{item.lastUpdate}
                </if>
            </foreach>
        </trim>
    </trim>
    where epc in
    <foreach collection="list" separator="," item="item" index="index" open="(" close=")">
        #{item.epc}
    </foreach>
</update>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容