有这样的需求,需要批量更新一堆数据,选择for循环挨个更新的效率肯定比较低,我们可以采用批量更新的方法,
批量更新的mapper语句如下,demo:
<update id="updatebatchF" parameterType="java.util.List"> UPDATE flower <trim prefix="set" suffixOverrides=","> <trim prefix="price =case" suffix="end,"> <foreach collection="list" item="item" index="index"> <if test="item.price !=null"> when id=#{item.id} then #{item.price} </if> </foreach> </trim> <trim prefix="production =case" suffix="end,"> <foreach collection="list" item="item" index="index"> <if test="item.production !=null"> when id=#{item.id} then #{item.production} </if> </foreach> </trim> </trim> where id in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item.id,jdbcType=BIGINT} </foreach> </update>
下面是正常的操作:
<update id="updatesingle" parameterType="xin.nimil.testmbs.pojo.Flower"> update flower set price = #{price},production=#{production} where id = #{id} </update>
两种对比:
long s = System.currentTimeMillis(); List<Flower> flowers = Arrays.asList(Flower.builder().id(1).price(2.0).production("沂源si").build(), Flower.builder().id(2).price(2.0).production("沂源qw").build()); flowers.forEach(e->testMbFlower.updatesingle(e)); return System.currentTimeMillis()-s;
long s = System.currentTimeMillis(); List<Flower> flowers = Arrays.asList(Flower.builder().id(1).price(1.0).production("沂源xi").build(), Flower.builder().id(2).price(1.0).production("沂源xi").build()); testMbFlower.updatebatchF(flowers); return System.currentTimeMillis()-s;
第一种for循环的更新方法耗时503
第二种批处理更新方法耗时 433
效率提升了,这还是两个数据的情况,当数据量很大的时候肯定会提升的效率更加庞大