在公司ERP项目开发中,遇到批量数据插入或者更新,因为每次连接数据库比较耗时,所以决定改为批量操作,提升效率。库存盘点导入时,需要大量数据批量操作。
1:数据库连接代码中必须开启批量操作。加上这句,&allowMultiQueries=true,完整的如下:
jdbc:mysql://localhost:3306/jeesite2016?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
2:批量更新 ,注意update的separator是;,和批量插入的不一样。
<update id="batchUpdateQuantity" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="" close="" separator=";"> update erp_store <set> quantity=#{item.quantity}, update_date=#{item.updateDate} </set> where id = #{item.id} </foreach> </update>
经测试,一共1662条数据,批量插入用时466ms,循环单独插入用时1898ms。可以批量操作效率高很多。
3、批量插入
扫描二维码关注公众号,回复:
305446 查看本文章
<insert id="batchInsert"> INSERT INTO erp_store_detail( id, store_id, type, change_quantity, after_quantity, update_date, remarks, link_id ) VALUES <foreach collection="list" item="item" index="index" separator="," > ( #{item.id}, #{item.store.id}, #{item.type}, #{item.changeQuantity}, #{item.afterQuantity}, #{item.updateDate}, #{item.remarks}, #{item.linkId} ) </foreach> </insert>