批量更新的注意事項 原

小弟昨日一個需求,就是講一個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文檔再議。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章