寫於20210618 21:00 北京望京
數據庫
借於不少人不會 mybatis 批量更新,特此記錄。bash
微信搜:JavaPub ,有疑惑留言。微信
當咱們在作更新或者是插入操做時,數據爲多對多、一一對應的狀況markdown
例如:mybatis
編號。 名字。 狀態 1。 tom 0 2。 jerry. 0 3。 jeck. 1
代碼中循環寫入、更新這是大多數人作法,可是確定不是最優解ide
這裏數據庫中存儲了下劃線式,代碼中用駝峯式。atom
這裏是經過userId修改userStatus。當user_id爲1時、user_status爲0,當user_id爲3時、user_status爲1。spa
<update id="updateBatch"> update <include refid="tableName"/> <trim prefix="set" suffixOverrides=","> <trim prefix="user_status =case" suffix="end,"> <foreach collection="list" item="i" index="index"> <if test="i.userId!=null"> when user_id=#{i.userId} then #{i.userStatus} </if> </foreach> </trim> </trim> where user_id in <foreach collection="list" item="i" index="index" open="(" separator="," close=")"> #{i.userId} </foreach> </update>
<trim 屬性說明.net
可是你們要注意一點,這種狀況若是出錯,咱們並不知道是哪條錯誤,若是使用事務,就會所有回滾,好的辦法就是一次批量一部分,分擔出錯機率。code
參考: https://blog.csdn.net/lu1024188315/article/details/78758943 https://blog.csdn.net/xyjawq1/article/details/74129316