MyBatis 批量插入的 3 种方式!还有谁不会?

news/2024/5/18 22:59:10 标签: 数据库, mybatis, sqlserver, jdbc, js
js_content">

点击上方“果汁简历”,选择“置顶公众号”

数据库使用的是sqlserver,JDK版本1.8,运行在SpringBoot环境下,对比3种可用的方式:

  1. 反复执行单条插入语句

  2. xml拼接sql

  3. 批处理执行

先说结论:少量插入请使用反复插入单条数据,方便。数量较多请使用批处理方式。(可以考虑以有需求的插入数据量20条左右为界吧,在我的测试和数据库环境下耗时都是百毫秒级的,方便最重要)。

无论何时都不用xml拼接sql的方式

代码

拼接SQL的xml

newId()是sqlserver生成UUID的函数,与本文内容无关

<insert id="insertByBatch" parameterType="java.util.List">
    INSERT INTO tb_item VALUES
    <foreach collection="list" item="item" index="index" separator=",">
        (newId(),#{item.uniqueCode},#{item.projectId},#{item.name},#{item.type},#{item.packageUnique},
        #{item.isPackage},#{item.factoryId},#{item.projectName},#{item.spec},#{item.length},#{item.weight},
        #{item.material},#{item.setupPosition},#{item.areaPosition},#{item.bottomHeight},#{item.topHeight},
        #{item.serialNumber},#{item.createTime}</foreach>
</insert>

Mapper接口

Mapper是 mybatis插件tk.Mapper 的接口,与本文内容关系不大

public interface ItemMapper extends Mapper<Item> {
    int insertByBatch(List<Item> itemList);
}

Service类

@Service
public class ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    //批处理
    @Transactional
    public void add(List<Item> itemList) {
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
        ItemMapper mapper = session.getMapper(ItemMapper.class);
        for (int i = 0; i < itemList.size(); i++) {
            mapper.insertSelective(itemList.get(i));
            if(i%1000==999){//每1000条提交一次防止内存溢出
                session.commit();
                session.clearCache();
            }
        }
        session.commit();
        session.clearCache();
    }
    //拼接sql
    @Transactional
    public void add1(List<Item> itemList) {
        itemList.insertByBatch(itemMapper::insertSelective);
    }
    //循环插入
    @Transactional
    public void add2(List<Item> itemList) {
        itemList.forEach(itemMapper::insertSelective);
    }
}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ApplicationBoot.class)
public class ItemServiceTest {
    @Autowired
    ItemService itemService;

    private List<Item> itemList = new ArrayList<>();
    //生成测试List
    @Before 
    public void createList(){
        String json ="{\n" +
                "        \"areaPosition\": \"TEST\",\n" +
                "        \"bottomHeight\": 5,\n" +
                "        \"factoryId\": \"0\",\n" +
                "        \"length\": 233.233,\n" +
                "        \"material\": \"Q345B\",\n" +
                "        \"name\": \"TEST\",\n" +
                "        \"package\": false,\n" +
                "        \"packageUnique\": \"45f8a0ba0bf048839df85f32ebe5bb81\",\n" +
                "        \"projectId\": \"094b5eb5e0384bb1aaa822880a428b6d\",\n" +
                "        \"projectName\": \"项目_TEST1\",\n" +
                "        \"serialNumber\": \"1/2\",\n" +
                "        \"setupPosition\": \"1B柱\",\n" +
                "        \"spec\": \"200X200X200\",\n" +
                "        \"topHeight\": 10,\n" +
                "        \"type\": \"Steel\",\n" +
                "        \"uniqueCode\": \"12344312\",\n" +
                "        \"weight\": 100\n" +
                "    }";
        Item test1 = JSON.parseObject(json,Item.class);
        test1.setCreateTime(new Date());
        for (int i = 0; i < 1000; i++) {//测试会修改此数量
            itemList.add(test1);
        }
    }
     //批处理
    @Test
    @Transactional
    public void tesInsert() {
        itemService.add(itemList);
    }
    //拼接字符串
    @Test
    @Transactional
    public void testInsert1(){
        itemService.add1(itemList);
    }
    //循环插入
    @Test
    @Transactional
    public void testInsert2(){
        itemService.add2(itemList);
    }
}

测试结果:

10条 25条数据插入经多次测试,波动性较大,但基本都在百毫秒级别

方式50条100条500条1000条
批处理159ms208ms305ms432ms
xml拼接sql208ms232ms报错报错
反复单条插入1013ms2266ms8141ms18861ms

其中 拼接sql方式在插入500条和1000条时报错(似乎是因为sql语句过长,此条跟数据库类型有关,未做其他数据库的测试):com.microsoft.sqlserver.jdbc.SQLServerException: 传入的表格格式数据流(TDS)远程过程调用(RPC)协议流不正确。此 RPC 请求中提供了过多的参数。最多应为 2100

可以发现

  • 循环插入的时间复杂度是 O(n),并且常数C很大

  • 拼接SQL插入的时间复杂度(应该)是 O(logn),但是成功完成次数不多,不确定

  • 批处理的效率的时间复杂度是 O(logn),并且常数C也比较小

结论

循环插入单条数据虽然效率极低,但是代码量极少,在使用tk.Mapper的插件情况下,仅需代码,:

@Transactional
public void add1(List<Item> itemList) {
    itemList.forEach(itemMapper::insertSelective);
}

因此,在需求插入数据数量不多的情况下肯定用它了。

xml拼接sql是最不推荐的方式,使用时有大段的xml和sql语句要写,很容易出错,工作效率很低。更关键点是,虽然效率尚可,但是真正需要效率的时候你挂了,要你何用?

批处理执行是有大数据量插入时推荐的做法,使用起来也比较方便。

作者:楼主楼主
链接:https://urlify.cn/aayyMr

往期精彩回顾

让人又爱又恨的 Lombok,到底该不该用

Delombok 是个啥?居然可破 Lombok?

跳槽的必要条件是有一份好的简历

时候为自己的后半生考虑了——致奔三的互联网人

点个赞呗


http://www.niftyadmin.cn/n/1332039.html

相关文章

在项目中用了Arrays.asList、ArrayList的subList,被公开批评

点击上方“果汁简历”&#xff0c;选择“置顶公众号”1. 使用Arrays.asList的注意事项1.1 可能会踩的坑先来看下Arrays.asList的使用&#xff1a;List<Integer> statusList Arrays.asList(1, 2); System.out.println(statusList); System.out.println(statusList.contai…

IDEA这样配置注释模板,让你高出一个逼格!!

作者: Jitwxs 链接: https://urlify.cn/URB7ve一、类注释打开 IDEA 的 Settings&#xff0c;点击 Editor-->File and Code Templates&#xff0c;点击右边 File 选项卡下面的 Class&#xff0c;在其中添加图中红框内的内容&#xff1a;/*** author jitwxs* date ${YEAR}年${…

你还在 new 对象吗?Java8 通用 Builder 了解一下?

点击上方“果汁简历”&#xff0c;选择“置顶公众号”程序员经常会遇到灵魂拷问&#xff1a;你有对象吗&#xff1f;没有&#xff0c;但我可以 new 一个&#xff01;public class GirlFriend {private String name;private int age;// 省略 getter & setter ...public stat…

事务注解 @Transactional 失效的3种场景及解决办法

点击上方“果汁简历”&#xff0c;选择“置顶公众号”Transactional失效场景介绍第一种 Transactional注解标注方法修饰符为非public时&#xff0c;Transactional注解将会不起作用。例如以下代码。定义一个错误的Transactional标注实现&#xff0c;修饰一个默认访问符的方法/**…

RabbitMQ 七种队列模式应用场景案例分析(通俗易懂)

点击上方 果汁简历 &#xff0c;选择“置顶公众号”优质文章&#xff0c;第一时间送达作者&#xff1a;我思知我在blog.csdn.net/qq_32828253/article/details/110450249七种模式介绍与应用场景简单模式&#xff08;Hello World&#xff09;做最简单的事情&#xff0c;一个生产…

昨天还在 for 循环里写加号拼接字符串的那个同事,今天已经不在了

点击上方“果汁简历”&#xff0c;选择“置顶公众号”引言都说 StringBuilder 在处理字符串拼接上效率要强于 String&#xff0c;但有时候我们的理解可能会存在一定的偏差。最近我在测试数据导入效率的时候就发现我以前对 StringBuilder 的部分理解是错误的。后来我通过实践测试…

最牛逼的 Java 日志框架,性能无敌,横扫所有对手。。

点击上方 果汁简历 &#xff0c;选择“置顶公众号”优质文章&#xff0c;第一时间送达作者&#xff1a;空无链接&#xff1a;https://juejin.cn/post/6945753017878577165Logback 算是JAVA 里一个老牌的日志框架&#xff0c;从06年开始第一个版本&#xff0c;迭代至今也十几年了…

常用正则表达式最强整理(速查手册,收藏~)

点击上方“果汁简历”&#xff0c;选择“置顶公众号”一、校验数字的表达式数字&#xff1a;^[0-9]*$n位的数字&#xff1a;^\d{n}$至少n位的数字&#xff1a;^\d{n,}$m-n位的数字&#xff1a;^\d{m,n}$零和非零开头的数字&#xff1a;^(0|[1-9][0-9]*)$非零开头的最多带两位小…