Mybatis中4种批量插入测试

网上有很多关于批量插入的信息,但有些不全,没有代码,一些人无从下手。自己整理了一下,做一个测试,和简单的代码!

mybatis常见的批量插入有4种:代码for插入、sqlSession插入、拼接sql语句插入、xml文件中foreach插入。

本次测试的数据量为分别为200条、1000条、10000条。每种数据量进行了5次测试,取其中某一次进行记录,并没有取最低时间或最高时间。

1、java中的for循环

for(int i = 0; i < 10000; i++){
    mapper.insert(entity)
}

下面图片中左上角350为执行时间,单位毫秒

 

2、 sqlSession

@Autowired
SqlSessionFactory sqlSessionFactory;

private void insertBatch(List<Entity> list){
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
    try{
        EntityMapper entityMapper = sqlSession.getMapper(EntityMapper.class);
        list.forEach(entity -> {
            entityMapper.insert(entity);
        });
        sqlSession.commit();
        sqlSession.clearCache();
        sqlSession.close();
    }catch (Exception e){
        sqlSession.rollback();
        System.out.println(e.getMessage());
    }finally {
        if(sqlSession != null) sqlSession.close();
    }
    
}

 

3、xml文件中foreach插入

	<insert id="insert">
		INSERT INTO entity( name, age) 
        VALUES
        <foreach collection="list" item="item" index="index" separator=",">
            #{item.name},
            #{item.age})
        </foreach>
    </insert>

4、StringBuffer拼接sql

service文件中代码

List<Entity> list = new ArrayList<>();
entityMapper.insertBatchSql(list);

mapper.java文件中代码 

    /**
     * 拼接批量插入sql
     * @param list
     */
    @InsertProvider(type = Task.class, method = "insertListSql")
    void insertBatch(List<Entity> list);

Task.java文件中代码

public String insertListSql(List<Entity> list){
    StringBuffer sqlList = new StringBuffer();
    sqlList.append(" INSERT INTO user( name, age )  VALUES ");
    for (int i = 0; i < list.size() ; i++) {
        Entity entity = list.get(i);
        sqlList.append(" (").append("'").append(user.getName()).append("',").append(user.getAge()).append(")");
        if (i < list.size()-1) {
            sqlList.append(",");
        }
    }
    return sqlList.toString();
}

通过测试结果可以很明显看出每种方法的效率。
从高到低
1、sql拼接

2、sqlSession

3、mybatis中的foreach

4、 java中for循环


10000条数据。sql拼接的方式仅需要1秒左右,java中for循环需要18秒,sqlSession需要4秒左右。
sql拼接的方式最快,但需要拼接sql。推荐大家用sql的方式进行批量操作,不要怕麻烦!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值