关于mybatis+mysql批量插入的问题

本文讨论了在使用Mybatis与MySQL进行数据批量插入时遇到的问题。传统的逐条插入方式由于频繁建立数据库连接,导致效率低下。通过批量插入,可以显著减少数据库交互次数,提高性能。文中提到了XML配置中批量插入的实现方式,并暗示会举例说明不同SQL写法对执行效率的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  之前在写项目时,会遇到在某个时间点内需要插入多条数据。之前我采用的方式是一次循环插入一条数据,每次插入都是一个过程。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
做个小笔记~



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值