在公司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、批量插入  

<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>

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐