In the development of the company's ERP project, when encountering batch data insertion or update, it is time-consuming to connect to the database each time, so it is decided to change to batch operation to improve efficiency. When importing inventory, a large amount of data is required for batch operations.
1: Batch operations must be enabled in the database connection code. Add this sentence, &allowMultiQueries=true , the complete is as follows:
jdbc:mysql://localhost:3306/jeesite2016?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
2: Batch update, note that the separator of update is ;, which is different from batch insert.
<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>
After testing, there are a total of 1662 pieces of data, the batch insertion takes 466ms, and the loop insert takes 1898ms. It is much more efficient to operate in batches.
3. Batch insert
<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>