Mybatis中進行批量更新(updateBatch)
更新多條數據,每條數據都不一樣
背景描述:通常如果需要一次更新多條數據有兩個方式,(1)在業務代碼中循環遍歷逐條更新。(2)一次性更新所有數據(更准確的說是一條sql語句來更新所有數據,逐條更新的操作放到數據庫端,在業務代碼端展現的就是一次性更新所有數據)。兩種方式各有利弊,下面將會對兩種方式的利弊做簡要分析,主要介紹第二種方式在mybatis中的實現。
逐條更新(效率低)(方法一)
這種方式顯然是最簡單,也最不容易出錯的,即便出錯也只是影響到當條出錯的數據,而且可以對每條數據都比較可控,更新失敗或成功,從什么內容更新到什么內容,都可以在邏輯代碼中獲取。代碼可能像下面這個樣子:
1 updateBatch(List<MyData> datas){ 2 for(MyData data : datas){ 3 try{ 4 myDataDao.update(data);//更新一條數據,mybatis中如下面的xml文件的update 5 } 6 catch(Exception e){ 7 ...//如果更新失敗可以做一些其他的操作,比如說打印出錯日志等 8 } 9 } 10 } 11 12 //mybatis中update操作的實現 13 <update> 14 update mydata 15 set ... 16 where ... 17 </update>
這種方式最大的問題就是效率問題,逐條更新,每次都會連接數據庫,然后更新,再釋放連接資源(雖然通過連接池可以將頻繁連接數據的效率大大提高,抗不住數據量大),這中損耗在數據量較大的時候便會體現出效率問題。這也是在滿足業務需求的時候,通常會使用上述提到的第二種批量更新的實現(當然這種方式也有數據規模的限制,后面會提到)。
逐條更新(方法二)
通過循環,依次執行多條update的sql
前提條件:
要實現批量更新,首先得設置mysql支持批量操作,在jdbc鏈接中需要附加&allowMultiQueries=true屬性才行 例如: jdbc:mysql://localhost:3306/dbname?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
1 <update id="updateBatch" parameterType="java.util.List"> 2 <foreach collection="list" item="item" index="index" open="" close="" separator=";"> 3 update course 4 <set> 5 name=${item.name} 6 </set> 7 where id = ${item.id} 8 </foreach> 9 </update>
一條記錄update一次,性能比較差,容易造成阻塞。
sql批量更新(一)(主力)
(可行)實際實踐(傳入的是List<Map<String, Object>>)
++務必注意:一定要加where條件,里面的id為需要更新的數據的id;如果不加where條件,則會全部更新,但是需要更新且有數據的更新為傳遞的數據,沒有數據的則更新為null,此時更新出錯++
1 <update id="updateChartParamByAccountAndChartid" parameterType="list"> 2 update followme_parameters 3 <trim prefix="set" suffixOverrides=","> 4 <trim prefix="signal_source =case" suffix="end,"> 5 <foreach collection="list" item="item" index="index"> 6 <if test="item.signalSource!=null"> 7 when account=#{item.account} and chart_id=#{item.chartId} 8 then #{item.signalSource} 9 </if> 10 </foreach> 11 </trim> 12 <trim prefix="rate =case" suffix="end,"> 13 <foreach collection="list" item="item" index="index"> 14 <if test="item.rate!=null"> 15 when account=#{item.account} and chart_id=#{item.chartId} 16 then #{item.rate} 17 </if> 18 </foreach> 19 </trim> 20 </trim> 21 where id in 22 <foreach collection="list" item="item" index="index" separator="," open="(" close=")"> 23 #{item.id} 24 </foreach> 25 </update>
下面逐步講解
一條sql語句來批量更新所有數據,下面直接看一下在mybatis中通常是怎么寫的(去掉mybatis語法就是原生的sql語句了,所有就沒單獨說sql是怎么寫的)。
1 <update id="updateBatch" parameterType="java.util.List"> 2 update mydata_table 3 set status= 4 <foreach collection="list" item="item" index="index" 5 separator=" " open="case ID" close="end"> 6 when #{item.id} then #{item.status} 7 </foreach> 8 where id in 9 <foreach collection="list" index="index" item="item" 10 separator="," open="(" close=")"> 11 #{item.id,jdbcType=BIGINT} 12 </foreach> 13 </update>
其中when...then...是sql中的"switch" 語法。這里借助mybatis的語法來拼湊成了批量更新的sql,上面的意思就是批量更新id在updateBatch參數所傳遞List中的數據的status字段。還可以使用實現同樣的功能,代碼如下:
1 <update id="updateBatch" parameterType="java.util.List"> 2 update mydata_table 3 <trim prefix="set" suffixOverrides=","> 4 <trim prefix="status =case" suffix="end,"> 5 <foreach collection="list" item="item" index="index"> 6 when id=#{item.id} then #{item.status} 7 </foreach> 8 </trim> 9 </trim> 10 where id in 11 <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> 12 #{item.id,jdbcType=BIGINT} 13 </foreach> 14 </update> 15 16 <trim>
屬性說明
1.prefix,suffix 表示在trim標簽包裹的部分的前面或者后面添加內容 2.如果同時有prefixOverrides,suffixOverrides 表示會用prefix,suffix覆蓋Overrides中的內容。 3.如果只有prefixOverrides,suffixOverrides 表示刪除開頭的或結尾的xxxOverides指定的內容。
上述代碼轉化成sql如下:
1 update mydata_table 2 set status = 3 case 4 when id = #{item.id} then #{item.status}//此處應該是<foreach>展開值 5 ... 6 end 7 where id in (...);
當然這是最簡單的批量更新實現,有時候可能需要更新多個字段,那就需要將
1 <trim prefix="status =case" suffix="end,"> 2 <foreach collection="list" item="item" index="index"> 3 when id=#{item.id} then #{item.status} 4 </foreach> 5 </trim>
復制拷貝多次,更改prefix和when...then...的內容即可.而如果當需要為某個字段設置默認值的時候可以使用else
1 <trim prefix="status =case" suffix="end,"> 2 <foreach collection="list" item="item" index="index"> 3 when id=#{item.id} then #{item.status} 4 </foreach> 5 else default_value 6 </trim>
還有更常見的情況就是需要對要更新的數據進行判斷,只有符合條件的數據才能進行更新,這種情況可以這么做:
1 <trim prefix="status =case" suffix="end,"> 2 <foreach collection="list" item="item" index="index"> 3 <if test="item.status !=null and item.status != -1"> 4 when id=#{item.id} then #{item.status} 5 </if> 6 </foreach> 7 </trim>
這樣的話只有要更新的list中status != null && status != -1的數據才能進行status更新.其他的將使用默認值更新,而不會保持原數據不變.如果要保持原數據不變呢?即滿足條件的更新,不滿足條件的保持原數據不變,簡單的來做就是再加一個,因為mybatis中沒有if...else...語法,但可以通過多個實現同樣的效果,如下:
1 <trim prefix="status =case" suffix="end,"> 2 <foreach collection="list" item="item" index="index"> 3 <if test="item.status !=null and item.status != -1"> 4 when id=#{item.id} then #{item.status} 5 </if> 6 <if test="item.status == null or item.status == -1"> 7 when id=#{item.id} then mydata_table.status //這里就是原數據 8 </if> 9 </foreach> 10 </trim>
整體批量更新的寫法如下: (親測有效)
1 <update id="updateBatch" parameterType="java.util.List"> 2 update mydata_table 3 <trim prefix="set" suffixOverrides=","> 4 <trim prefix="status =case" suffix="end,"> 5 <foreach collection="list" item="item" index="index"> 6 <if test="item.status !=null and item.status != -1"> 7 when id=#{item.id} then #{item.status} 8 </if> 9 <if test="item.status == null or item.status == -1"> 10 when id=#{item.id} then mydata_table.status//原數據 11 </if> 12 </foreach> 13 </trim> 14 </trim> 15 where id in 16 <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> 17 #{item.id,jdbcType=BIGINT} 18 </foreach> 19 </update>
批量更新(單個字段,傳參list),實際是sql批量更新的簡化版本而已
單個字段
<update id="updateByBatch" parameterType="java.util.List"> update t_goods set NODE_ID= <foreach collection="list" item="item" index="index" separator=" " open="case" close="end"> when GOODS_ID=#{item.goodsId} then #{item.nodeId} </foreach> where GOODS_ID in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item.goodsId,jdbcType=BIGINT} </foreach> </update>
單個字段方法二
<update id="updateByBatch" parameterType="java.util.List"> UPDATE t_goods SET NODE_ID = CASE <foreach collection="list" item="item" index="index"> WHEN GOODS_ID = #{item.goodsId} THEN #{item.nodeId} </foreach> END WHERE GOODS_ID IN <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item.goodsId} </foreach> </update>
以上單字段更新實際執行:
UPDATE t_goods SET NODE_ID = CASE WHEN GOODS_ID = ? THEN ? END WHERE GOODS_ID IN ( ? )
sql批量更新(二)
傳入的是List<Map<String,Object>>
直接運行插入,如果有插入的數據轉為更新該條數據
1 <insert id="updateChartParamByAccountAndChartid"> 2 insert into followme_parameters 3 (account,chart_id,signal_source,rate) 4 values 5 <foreach collection="list" separator="," index="index" item="item"> 6 (#{item.account},#{item.chartId},#{item.signalSource},#{item.rate}) 7 </foreach> 8 ON duplicate KEY UPDATE 9 signal_source=values(signal_source),rate=values(rate) 10 11 </insert>
更新多條數據,更新的內容一樣.
方法一,傳map/ 傳String
NODE_ID從map中取出來,goodsIdList是字符串拼接好的(如下面的"1,2,5")
<update id="updateByBatchPrimaryKey" parameterType="java.util.Map"> UPDATE t_goods SET NODE_ID = #{nodeId} WHERE GOODS_ID IN (${goodsIdList}) </update>
實際的sql
1 UPDATE t_goods SET NODE_ID = ? WHERE GOODS_ID IN (1,2,5);
方法二,傳map/傳list
NODE_ID從map中取出來,goodsIdList是用list拼接出來的
1 <update id="updateByBatchPrimaryKey" parameterType="java.util.Map"> 2 UPDATE t_goods 3 SET NODE_ID = #{nodeId} 4 WHERE GOODS_ID IN 5 <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> 6 #{item.goodsId} 7 </foreach> 8 </update>
實際的sql
UPDATE t_goods SET NODE_ID = ? WHERE GOODS_ID IN (1,2,5);
站在巨人的肩膀上摘蘋果:
主力:https://blog.csdn.net/xyjawq1/article/details/74129316/
輔助:https://www.jianshu.com/p/041bec8ae6d3