mybatis批量更新表字段数据

1、批量更新,首先要确定每次批量更新的数据量,以减轻数据库压力,因此我们需要定义常量:batchSize = 100或你自己合适的大小。

2、定义好了常量我们就需要将所有要更新的对象放到List中,如List<‘YourEntity’> updateList;

3、编写拆分并更新核心方法。

		if(CollectionUtils.isEmpty(updateList)){
            return 0;
        }
        if(updateList.size() <= batchSize){
            return yourUpdateMapper.batchUpdateYourEntity(updateList);
        }
        List<List<YourEntity>> partList = Lists.partition(updateList, batchSize);
        int sum = 0;
        for(List<YourEntity> batchList : partList){
            sum += yourUpdateMapper.batchUpdateYourEntity(batchList);
        }
        return sum;

4、编写对应mapper接口

public int batchUpdateYourEntity(@Param("batchList") List<YourEntity> batchList);

5、编写Mybatis配置xml

<update id="batchUpdateYourEntity">
        update your_table_name mydata_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="your_colume_name1 =case" suffix="end,">
                <foreach collection="batchList" item="item" index="index">
                    <if test="item.youEntityField1 !=null and item.youEntityField1 &gt; 0">
                        when your_table_primary_id = #{item.yourEntityPrimaryFiled}
                        then #{item.youEntityField1}
                    </if>
                    <if test="item.youEntityField1 == null or item.youEntityField1 &lt;= 0">
                        when your_table_primary_id = #{item.yourEntityPrimaryFiled}
                        then mydata_table.your_colume_name1 
                    </if>
                </foreach>
                上面这个字段是数字类型的,当数值大于0时才更新,<=0时还用表字段原值即不更新,符号要用转义码
            </trim>
            <trim prefix="update_time =case" suffix="end,">
                <foreach collection="batchList" item="item" index="index">
                    <if test="item.updateTime !=null">
                        when your_table_primary_id = #{item.yourEntityPrimaryFiled}
                        then #{item.updateTime}
                    </if>
                    <if test="item.updateTime== null">
                        when your_table_primary_id = #{item.yourEntityPrimaryFiled}
                        then mydata_table.update_time 
                    </if>
                </foreach>
                上面这个是字符串修改日期,传入属性字段非空则修改,空就使用表字段原值
            </trim>
        </trim>
        where your_table_primary_id in
        <foreach collection="batchList" item="item" index="index" separator="," open="(" close=")">
            #{item.yourEntityPrimaryFiled}
        </foreach>
    </update>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值