之前在写项目时,会遇到在某个时间点内需要插入多条数据。之前我采用的方式是一次循环插入一条数据,每次插入都是一个过程。1.发起与数据库的链接 2.插入一条数据。
当你需要批量插入成千上万条的时候。就会是这个数量级乘以2,相信大部分的时间是浪费在链接数据库上。
批量插入成千上万条数据,就只需要2个步骤了,链接数据量,插入数据,当然插入数据的时候sql的不同写法,那么执行的效率也会不同,待会我会举一个小栗子。
xml中的写法
<insert id="addDemoList" parameterType="ArrayList">
INSERT INTO `demo` ( userId, financingId`,smashed, bonusAmount)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
( #{item.userId}, #{item.financingId},#{item.smashed}, #{item.bonusAmount})
</foreach>
</insert>
传入的参数是一个list
在Mapper中的接口
void addDemoList(List<Demo> item);
传入的是的一个实体的list,当然也可以是map的list。具体用哪个可以根据实际情况来使用。上述xml中打印出来的sql会是这样的
INSERT INTO `smasheggrecord` ( userId, financingId,smashed, bonusAmount) VALUES
(#{item.userId}, #{item.financingId}, #{item.smashed}, #{item.bonusAmount}),(#{item.userId}, #{item.financingId}, #{item.smashed}, #{item.bonusAmount}),(#{item.userId}, #{item.financingId}, #{item.smashed}, #{item.bonusAmount}),(#{item.userId}, #{item.financingId}, #{item.smashed}, #{item.bonusAmount})没错,就是这样一个形式。这样的好处是sql只执行一遍,速度会很快。如果是INSERT INTO `smasheggrecord` ( userId, financingId,smashed, bonusAmount) VALUES(#{item.userId}, #{item.financingId}, #{item.smashed}, #{item.bonusAmount});
INSERT INTO `smasheggrecord` ( userId, financingId,smashed, bonusAmount) VALUES(#{item.userId}, #{item.financingId}, #{item.smashed}, #{item.bonusAmount});
...INSERT INTO `smasheggrecord` ( userId, financingId,smashed, bonusAmount) VALUES(#{item.userId}, #{item.financingId}, #{item.smashed}, #{item.bonusAmount});
这样的形式,那么sql就会执行对应的次数。这也无形的减慢了插入的速度。另外再插一句和这个无关的,如果前端POST过来一个请求,有2个参数和值全都是一模一样,那么后台拿到的会是怎么样的呢?栗子:参数1:params:123参数2:params:123那么后台将会拿到的是params:123,123做个小笔记~