mybatis执行批量更新batch update 的方法

本文介绍了数据库连接配置中允许多查询的重要性,并展示了MyBatis中进行批量更新和插入的示例,包括条件判断和on duplicate key update策略的应用,适用于数据同步和维护场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、数据库连接必须配置:&allowMultiQueries=true

  我的配置如下:jdbc:mysql://10.20.13.16:3306/CALENDAR?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true

2、批量修改并加判断条件(修改字段可选)

    <!-- 批量更新赛程 -->
    <update id="updateMatchs" parameterType="java.util.List">
        <foreach collection="matchs" item="item" index="index" open="" close="" separator=";">
            update t_match
            <set>
                <if test="item.title !=null">
                    TITLE = #{item.title,jdbcType=VARCHAR},
                </if>
                <if test="item.homeScore !=null">
                    HOME_SCORE = #{item.homeScore,jdbcType=INTEGER},
                </if>
                <if test="item.visitScore !=null">
                    VISTT_SCORE = #{item.visitScore,jdbcType=INTEGER},
                </if>
                <if test="item.liveSource !=null">
                    LIVE_SOURCE = #{item.liveSource,jdbcType=VARCHAR},
                </if>
                <if test="item.liveURL !=null">
                    LIVE_URL = #{item.liveURL,jdbcType=VARCHAR},
                </if>
                <if test="item.isHotMatch !=null">
                    IS_HOT_MATCH = #{item.isHotMatch,jdbcType=VARCHAR}
                </if>
            </set>
        where HOME_TEAM_ID = #{item.homeTeamId,jdbcType=VARCHAR} and
        VISIT_TEAM_ID = #{item.visitTeamId,jdbcType=VARCHAR} and
        MATCH_TIME = #{item.matchTime,jdbcType=BIGINT}
        </foreach>
    </update>
java接口

    /**
     * 批量修改赛程
     *
     * @param matchs
     * @throws DaoException
     */
    void updateMatchs(@Param(value = "matchs")List<MatchBasic> matchs);

不配置情况下,利用 on duplicate key update

 <!-- 批量新增或者修改 -->
    <insert id="insertOrUpdateBatch">
        insert into product_specifications(id,product_basic_code, title_1, value_1, title_2, value_2, selling_price,
        stock, cost_price, img_url)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.id},#{entity.productBasicCode}, #{entity.title1}, #{entity.value1}, #{entity.title2},
            #{entity.value2}, #{entity.sellingPrice}, #{entity.stock}, #{entity.costPrice},
            #{entity.imgUrl})
        </foreach>
        on duplicate key update
        id = values(id),product_basic_code = values(product_basic_code) , title_1 = values(title_1) , value_1 =
        values(value_1) , title_2 = values(title_2) , value_2 = values(value_2) , selling_price = values(selling_price)
        , stock = values(stock) , cost_price = values(cost_price) ,img_url = values(img_url)
    </insert>

### MyBatis 批量更新最佳实践 #### 使用 `foreach` 实现批量更新 为了提高性能并减少数据库连接次数,在处理大量数据时推荐使用批处理功能。可以通过 `<foreach>` 标签来构建动态SQL语句,从而实现高效的批量更新操作[^1]。 ```xml <update id="batchUpdate" parameterType="java.util.List"> UPDATE user_info <set> <foreach collection="list" item="item" separator=","> (id=#{item.id},name=#{item.name}) </foreach> </set> </update> ``` 上述代码存在语法错误,正确的做法是在 SET 子句内指定列名,并利用 WHERE 来匹配记录: ```xml <update id="batchUpdateUsers" parameterType="java.util.List"> UPDATE users u <set> <if test="item.username != null">u.username = #{item.username},</if> <if test="item.email != null">u.email = #{item.email}</if> </set> WHERE u.id IN ( <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item.id} </foreach> ) </update> ``` 此方法适用于需要针对多个字段执行部分更新的情况。对于每个传入的对象实例,仅当相应属性不为空时才会被纳入到SET子句中去[^3]。 #### 利用 JDBCBatch 功能 另一种更高效的方式是借助JDBC底层支持的Batch特性来进行大批量的数据更新工作。这种方式能够显著降低网络开销,提升整体吞吐率[^4]。 Java Mapper接口定义如下所示: ```java public interface UserMapper { void batchUpdate(@Param("users") List<User> users); } ``` 对应的XML映射文件配置则应采用以下形式: ```xml <update id="batchUpdate" parameterType="java.util.List"> START TRANSACTION; <foreach collection="list" item="user" separator=";"> UPDATE users SET username=#{user.username}, email=#{user.email} WHERE id=#{user.id}; </foreach> COMMIT; </update> ``` 需要注意的是,以上事务控制命令 (`START TRANSACTION;`, `COMMIT`) 可能会因不同的数据库产品而有所不同;另外,某些情况下可能还需要调整MyBatis默认的行为以启用真正的批处理模式[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值