MyBatis SQL 批量更新(代碼➕案例)

寫於20210618 21:00 北京望京數據庫

借於不少人不會 mybatis 批量更新,特此記錄。bash


微信搜:JavaPub ,有疑惑留言。微信

1.場景

當咱們在作更新或者是插入操做時,數據爲多對多、一一對應的狀況markdown

例如:mybatis

編號。  名字。  狀態
1。  tom    0
2。  jerry.   0
3。  jeck.   1

代碼中循環寫入、更新這是大多數人作法,可是確定不是最優解ide

2.MyBatis XML

  • 先直接上個終極版

這裏數據庫中存儲了下劃線式,代碼中用駝峯式。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

  1. prefix,suffix 表示在 trim 標籤包裹的部分的前面或者後面添加內容
  2. 若是同時有 prefixOverrides,suffixOverrides 表示會用 prefix,suffix 覆蓋 Overrides 中的內容。
  3. 若是隻有 prefixOverrides,suffixOverrides 表示刪除開頭的或結尾的 xxxOverides 指定的內容。

3.重點

可是你們要注意一點,這種狀況若是出錯,咱們並不知道是哪條錯誤,若是使用事務,就會所有回滾,好的辦法就是一次批量一部分,分擔出錯機率。code


參考: https://blog.csdn.net/lu1024188315/article/details/78758943 https://blog.csdn.net/xyjawq1/article/details/74129316

相關文章
相關標籤/搜索