mybatis批量更新有两种方式
1 第一种就是普通的循环每条数据进行更新,这种方式最大的问题就是效率问题,逐条更新,每次都会连接数据库,然后更新,再释放连接资源(虽然通过连接池可以将频繁连接数据的效率大大提高,抗不住数据量大),这中损耗在数据量较大的时候便会体现出效率问题。这也是在满足业务需求的时候,通常会使用下面的这种批量更新进行实现(当然这种方式也有数据规模的限制,后面会提到)。
2 就是case when的写法 ,我自己实际开发中测试了,确实速度快
<update id="publish" parameterType="java.util.List">
update FLIGHT_AIRLINE
<trim prefix="set" suffixOverrides=",">
<trim prefix="PUBLISH_STATUS=case" suffix="end,">
<foreach collection="list" item="cus" index="index">
when ID=#{cus.id} then '1'
</foreach>
</trim>
<trim prefix="EFFECT_TIME=case" suffix="end,">
<foreach collection="list" item="cus" index="index">
<if test="cus.effectTime != null">
when ID=#{cus.id} then #{cus.effectTime}
</if>
</foreach>
</trim>
<trim prefix="UNEFFECT_TIME=case" suffix="end,">
<foreach collection="list" item="cus" index="index">
<if test="cus.uneffectTime != null">
when ID=#{cus.id} then #{cus.uneffectTime}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="cus" index="index">
ID=#{cus.id}
</foreach>
</update>
对于数据量比较大 可以分批次执行 如下:
// 这里模拟dataList就是即将要更新的数据集合
ArrayList<Object> dataList = new ArrayList<>();
// 数据集合大小
int size = dataList.size();
// 分批次执行的数据量大小
int threshold=500;
// 执行集合分割下标
int index = 0;
while (true) {
if (index + threshold >= size) {
updateBatch(dataList.subList(index, size));
break;
} else {
updateBatch(dataList.subList(index, index + threshold));
index = index + threshold;
}
}