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 > 0">
when your_table_primary_id = #{item.yourEntityPrimaryFiled}
then #{item.youEntityField1}
</if>
<if test="item.youEntityField1 == null or item.youEntityField1 <= 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>