# mybatis实现批量更新

主要的实现方式有两种:

  1. 利用foreach标签循环整个SQL语句
  2. 利用case when语法

在详细介绍这两种用法之前,先说几点注意事项。

mybatis默认是不允许执行多条SQL语句的,并且insert与update语句默认不是返回影响行数,而是返回匹配行数,因此需要按照如下方式修改这两个配置:

# 配置mybatis连接数据库的url
# 多添加配置:allowMultiQueries useAffectedRows
# allowMultiQueries=true&useAffectedRows=true
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/database?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useAffectedRows=true

# 接下来示例批量更新的两种实现方式

# 1. 循环整个SQL语句
<update id="updateBatch"  parameterType="java.util.List">  
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update tableName
        <set>
            name=${item.name},
            name2=${item.name2}
        </set>
        where id = ${item.id}
    </foreach>      
</update>
# 2. case when

此类写法有多种,但要注意,大多时候都要加where条件去限制update数据的范围,否则会更新所有的数据,case中如果没有对应when,会将数据更新为null

示例一:

<update id="updateBatch" parameterType="java.util.List">
        update tableName
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="c_name =case" suffix="end,">
                <foreach collection="list" item="cus">
                    <if test="cus.name!=null">
                        when id=#{cus.id} then #{cus.name}
                    </if>
                </foreach>
            </trim>
            <trim prefix="c_age =case" suffix="end,">
                <foreach collection="list" item="cus">
                    <if test="cus.age!=null">
                        when id=#{cus.id} then #{cus.age}
                    </if>
                </foreach>
            </trim>
        </trim>
        <where>
            <foreach collection="list" separator="or" item="cus">
                id = #{cus.id}
            </foreach>
        </where>
</update>

示例二:

<update id="updateProductCargoSpace" parameterType="java.util.Map">
    update bs_package_product
    set cargo_space_id = case product_id
    <foreach collection="sotckChangeList" item="stock" separator=" ">
        when #{stock.productId} then #{stock.cargoSpaceId}
    </foreach>
    end
    where package_id = #{packageId}
</update>

示例三:

recevice_weight=
                        <foreach collection="boxList" index="index" item="map" open="case" close="END" >
                              when box_id =#{map.boxId} then #{map.receiveWeight}
                        </foreach>,
修改于: 8/11/2022, 3:17:56 PM