1. 程式人生 > >Mybatis中進行批量更新(updateBatch)

Mybatis中進行批量更新(updateBatch)

背景描述:通常如果需要一次更新多條資料有兩個方式, (1)在業務程式碼中迴圈遍歷逐條更新。 (2)一次性更新所有資料(更準確的說是一條sql語句來更新所有資料,逐條更新的操作放到資料庫端,在業務程式碼端展現的就是一次性更新所有資料)。兩種方式各有利弊,下面將會對兩種方式的利弊做簡要分析,主要介紹第二種方式在mybatis中的實現。

逐條更新

這種方式顯然是最簡單,也最不容易出錯的,即便出錯也只是影響到當條出錯的資料,而且可以對每條資料都比較可控,更新失敗或成功,從什麼內容更新到什麼內容,都可以在邏輯程式碼中獲取。程式碼可能像下面這個樣子:

updateBatch(List<MyData
>
datas){ for(MyData data : datas){ try{ myDataDao.update(data);//更新一條資料,mybatis中如下面的xml檔案的update } catch(Exception e){ ...//如果更新失敗可以做一些其他的操作,比如說打印出錯日誌等 } } }12345678910
//mybatis中update操作的實現
<update>
    update mydata
    set   ...
    where ...
</
update
>
123456

這種方式最大的問題就是效率問題,逐條更新,每次都會連線資料庫,然後更新,再釋放連線資源(雖然通過連線池可以將頻繁連線資料的效率大大提高,抗不住資料量大),這中損耗在資料量較大的時候便會體現出效率問題。這也是在滿足業務需求的時候,通常會使用上述提到的第二種批量更新的實現(當然這種方式也有資料規模的限制,後面會提到)。

sql批量更新

一條sql語句來批量更新所有資料,下面直接看一下在mybatis中通常是怎麼寫的(去掉mybatis語法就是原生的sql語句了,所有就沒單獨說sql是怎麼寫的)。

<update id="updateBatch" parameterType
="java.util.List">
update mydata_table set status= <foreach collection="list" item="item" index="index" separator=" " open="case ID" close="end"> when #{item.id} then #{item.status} </foreach> where id in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item.id,jdbcType=BIGINT} </foreach> </update>12345678910111213

其中when…then…sql中的==“switch”== 語法。這裡藉助mybatisforeach語法來拼湊成了批量更新的sql,上面的意思就是批量更新idupdateBatch引數所傳遞List中的資料的status欄位。還可以使用trim實現同樣的功能,程式碼如下:

<update id="updateBatch" parameterType="java.util.List">
        update mydata_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="status =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                     when id=#{item.id} then #{item.status}
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
            #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>1234567891011121314

trim屬性說明

  1. prefix,suffix 表示在trim標籤包裹的部分的前面或者後面新增內容
  2. 如果同時有prefixOverrides,suffixOverrides 表示會用prefix,suffix覆蓋Overrides中的內容。
  3. 如果只有prefixOverrides,suffixOverrides 表示刪除開頭的或結尾的xxxOverides指定的內容。

上述程式碼轉化成sql如下:

    update mydata_table 
    set status = 
    case
        when id = #{item.id} then #{item.status}//此處應該是<foreach>展開值
        ...
    end
    where id in (...);1234567

當然這是最簡單的批量更新實現,有時候可能需要更新多個欄位,那就需要將

<trim prefix="status =case" suffix="end,">
     <foreach collection="list" item="item" index="index">
          when id=#{item.id} then #{item.status}
     </foreach>
</trim>12345

複製拷貝多次,更改prefixwhenthen…的內容即可.而如果當需要為某個欄位設定預設值的時候可以使用else

<trim prefix="status =case" suffix="end,">
     <foreach collection="list" item="item" index="index">
          when id=#{item.id} then #{item.status}
     </foreach>
     else default_value
</trim>123456

還有更常見的情況就是需要對要更新的資料進行判斷,只有符合條件的資料才能進行更新,這種情況可以這麼做:

<trim prefix="status =case" suffix="end,">
     <foreach collection="list" item="item" index="index">
         <if test="item.status !=null and item.status != -1">
             when id=#{item.id} then #{item.status}
         </if>
     </foreach>
</trim>1234567

這樣的話只有要更新的list中status != null && status != -1的資料才能進行status更新.其他的將使用預設值更新,而不會保持原資料不變.如果要保持原資料不變呢?即滿足條件的更新,不滿足條件的保持原資料不變,簡單的來做就是再加一個,因為mybatis中沒有if…else…語法,但可以通過多個實現同樣的效果,如下:

<trim prefix="status =case" suffix="end,">
     <foreach collection="list" item="item" index="index">
         <if test="item.status !=null and item.status != -1">
             when id=#{item.id} then #{item.status}
         </if>
         <if test="item.status == null or item.status == -1">
             when id=#{item.id} then mydata_table.status      //這裡就是原資料
         </if>
     </foreach>
</trim>12345678910

整體批量更新的寫法如下:

<update id="updateBatch" parameterType="java.util.List">
        update mydata_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="status =case" suffix="end,">
                 <foreach collection="list" item="item" index="index">
                     <if test="item.status !=null and item.status != -1">
                         when id=#{item.id} then #{item.status}
                     </if>
                     <if test="item.status == null or item.status == -1">
                         when id=#{item.id} then mydata_table.status//原資料
                     </if>
                 </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
            #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>12345678910111213141516171819

這種批量跟心資料庫的方式可以在一次資料庫連線中更新所有資料,避免了頻繁資料庫建立和斷開連線的開銷,可以很大程度的提高資料更新效率。但是這樣的問題是如果這個過程中更新出錯,將很難知道具體是哪個資料出錯,如果使用資料自身的事務保證,那麼一旦出錯,所有的更新將自動回滾。而且通常這種方式也更容易出錯。因此通常的使用的方案是進行折中,也就是一次批量更新一部分(分頁進行更新,比如說一共有1000條資料,一次更新100條)。這樣可以分擔出錯的概率,也更容易定位到出錯的位置。  當然如果資料量確實很大的時候,這種批量更新也一樣會導致更新效率低下(比如說一次更新100條,那如果10億條資料呢,一樣要批量更新1000萬次,建立和斷開1000萬次資料庫,這個效率是無法承受的)。這時候也許只能考慮其他方案了,比如引入快取機制等。