mybatis實現批量更新,更新的欄位也是動態的
阿新 • • 發佈:2019-02-18
把需要更新的引數封裝成一個物件list,需要注意list.add的是物件的引用!別重複使用一個物件封裝,要在for裡new物件封裝
然後把這個list傳到mapper.xml裡面用就行了;
mapper.java片段程式碼:
/**
* 批量調整庫存記錄
* @param lists
* @return
*/
int updateByEditS(List<PurchaseStock> lists);
mapper.java這裡不用寫成 int updateByEditS(@Param(value = "list") List<PurchaseStock> lists),只有傳普通引數的時候才要這樣寫。無論mapper.java裡傳的list什麼名字,只要這個list是arrayList型別的,在mapper.xml中的foreach中都是遍歷list就對了。
mapper.xml片段diamante:
<update id="updateByEditS" parameterType="java.util.List"> update purchase_stock <trim prefix="set" suffixOverrides=","> <trim prefix="price =case" suffix="end,"> <foreach collection="list" item="item" index="index"> <if test="item.price!=null"> when stock_id=#{item.stockId} then #{item.price} </if> </foreach> </trim> <trim prefix="out_num =case" suffix="end,"> <foreach collection="list" item="item" index="index"> <if test="item.outNum!=null"> when stock_id=#{item.stockId} then #{item.outNum} </if> </foreach> </trim> <trim prefix="stock_num =case" suffix="end,"> <foreach collection="list" item="item" index="index"> <if test="item.stockNum!=null"> when stock_id=#{item.stockId} then #{item.stockNum} </if> </foreach> </trim> </trim> where stock_id in <foreach collection="list" item="item" index="index" separator="," open="(" close=")"> #{item.stockId} </foreach> </update>
寫這個語句是為了滿足一個修改功能,就比如說上一個記錄是修改這個欄位,下一條記錄是修改另一個欄位,或者多個欄位一起修改。
封裝list物件的時候需要注意,如果不需要修改的屬性就不封裝進去,等到遍歷出來的時候自然就為null了!