批量更新的注意事項
阿新 • • 發佈:2018-11-27
小弟昨日一個需求,就是講一個list集合 update到一張表中,但與insert的寫法不同。需要將list封裝成map 在傳入xml中進行foreach
<update id="updateYesterdayAmountBatch" parameterType="java.util.Map"> update debt_current_user_holding_temp dcu set dcu.yesterday_amount = <foreach collection="tt" item="debtCurrentUserHoldingTemp" index="index" separator=" " open="case id" close="end,"> when #{debtCurrentUserHoldingTemp.id} then #{debtCurrentUserHoldingTemp.yesterdayAmount} </foreach> dcu.amount = <foreach collection="tt" item="debtCurrentUserHoldingTemp" index="index" separator=" " open="case id" close="end,"> when #{debtCurrentUserHoldingTemp.id} then #{debtCurrentUserHoldingTemp.amount} </foreach> dcu.updated_at = <foreach collection="tt" item="debtCurrentUserHoldingTemp" index="index" separator=" " open="case id" close="end"> when #{debtCurrentUserHoldingTemp.id} then #{debtCurrentUserHoldingTemp.updatedAt} </foreach> where dcu.id in <foreach collection="tt" index="index" item="debtCurrentUserHoldingTemp" separator="," open="(" close=")"> #{debtCurrentUserHoldingTemp.id} </foreach> </update>
這裡要注意,set 後面跟的欄位,要將open設定成 case id close = “end”,而where條件要使用in 原因是mybatis在解析時,會將其條件in(1,2,3)等等。而set 後面的欄位 會解析成 case id when xx then x when xxx then xxx end,下一個欄位,最後一個欄位是end 沒有逗號。
int updateYesterdayAmountBatch(Map<String, Object> tt);
上述是 mapper中的內容。這樣就能實現mybatis的批量更新。原因是mybatis預設會將list型別的引數自動封裝成map 並且key= list,vaue 就是集合。可是有時候直接傳入list也是可以的。不知道為什麼。按照我的寫法。如果直接傳入list引數 ,會報錯,parameter xxx not found。也不知是哪裡的問題。後續研究出來接著補充。
insert 使用list作為引數就能直接識別。。為啥update 必須要map呢?待小弟去研究一下mybatis文件再議。