[MyBatis]五分钟向MySql数据库插入一千万条数据 批量插入 用时5分左右

摘要:
我使用MyBatis的BatchInsert功能给数据表插入数据,其SQL在Mapper中定义成这样:˂?

本例代码下载:https://files.cnblogs.com/files/xiandedanteng/InsertMillionComparison20191012.rar

我的数据库环境是mysql Ver 14.14 Distrib 5.6.45, for Linux (x86_64) using EditLine wrapper

这个数据库是安装在T440p的虚拟机上的,操作系统为CentOs6.5.

插入一千万条数据,一次执行时间是4m57s,一次是5m。

数据表的定义是这样的:

CREATE TABLE`emp` (
  `Id` int(11) NOT NULLAUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` smallint(3) DEFAULT NULL,
  `cdate` timestamp NULL DEFAULT NULL COMMENT 'createtime',
  PRIMARY KEY(`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=13548008 DEFAULT CHARSET=utf8;

这是一个以id为自增主键,包含了三种不同类型字段的简单表。

我使用MyBatis的Batch Insert功能给数据表插入数据,其SQL在Mapper中定义成这样:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
                    "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hy.mapper.EmpMapper">
    <select id="selectById"resultType="com.hy.entity.Employee">
        select id,name,age,cdate as ctime  from emp where id=#{id}
    </select>
    <insert id="batchInsert">
        insert into emp(name,age,cdate)
        values
        <foreach collection="list"item="emp"separator=",">
            (#{emp.name},#{emp.age},#{emp.ctime,jdbcType=TIMESTAMP})
        </foreach>
    </insert>
</mapper>

与之对应的接口类是这样的:

packagecom.hy.mapper;
importjava.util.List;
importcom.hy.entity.Employee;
public interfaceEmpMapper {
    Employee selectById(longid);
    int batchInsert(List<Employee>emps);
}

实体类Employee如下:

packagecom.hy.entity;
importjava.text.MessageFormat;
public classEmployee {
    private longid;
    privateString name;
    private intage;
    privateString ctime;
    publicEmployee() {
    }
    public Employee(String name,intage,String ctime) {
        this.name=name;
        this.age=age;
        this.ctime=ctime;
    }
    publicString toString() {
        Object[] arr={id,name,age,ctime};
        String retval=MessageFormat.format("Employee id={0},name={1},age={2},created_datetime={3}", arr);
        returnretval;
    }
    public longgetId() {
        returnid;
    }
    public void setId(longid) {
        this.id =id;
    }
    publicString getName() {
        returnname;
    }
    public voidsetName(String name) {
        this.name =name;
    }
    public intgetAge() {
        returnage;
    }
    public void setAge(intage) {
        this.age =age;
    }
    publicString getCtime() {
        returnctime;
    }
    public voidsetCtime(String ctime) {
        this.ctime =ctime;
    }
}

如果插入数据不多可以这样书写:

packagecom.hy.action;
importjava.io.Reader;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.ibatis.io.Resources;
importorg.apache.ibatis.session.SqlSession;
importorg.apache.ibatis.session.SqlSessionFactory;
importorg.apache.ibatis.session.SqlSessionFactoryBuilder;
importorg.apache.log4j.Logger;
importcom.hy.entity.Employee;
importcom.hy.mapper.EmpMapper;
public classBatchInsert01 {
private static Logger logger = Logger.getLogger(SelectById.class);
    public static void main(String[] args) throwsException{
        Reader reader=Resources.getResourceAsReader("mybatis-config.xml");
        SqlSessionFactory ssf=newSqlSessionFactoryBuilder().build(reader);
        reader.close();
        SqlSession session=ssf.openSession();
        try{
            EmpMapper mapper=session.getMapper(EmpMapper.class);
            List<Employee> emps=new ArrayList<Employee>();
            emps.add(new Employee("Bill",22,"2018-12-25"));
            emps.add(new Employee("Cindy",22,"2018-12-25"));
            emps.add(new Employee("Douglas",22,"2018-12-25"));
            int changed=mapper.batchInsert(emps);
            System.out.println("changed="+changed);
            session.commit();
        }catch(Exception ex) {
            logger.error(ex);
            session.rollback();
        }finally{
            session.close();
        }
    }
}

如果插入数据多,就必须采用分批提交的方式,我采用的是插入一千个数据后提交一次,然后重复一万次的方式:

packagecom.hy.action;
importjava.io.Reader;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.ibatis.io.Resources;
importorg.apache.ibatis.session.SqlSession;
importorg.apache.ibatis.session.SqlSessionFactory;
importorg.apache.ibatis.session.SqlSessionFactoryBuilder;
importorg.apache.log4j.Logger;
importcom.hy.entity.Employee;
importcom.hy.mapper.EmpMapper;
public classBatchInsert1000 {
private static Logger logger = Logger.getLogger(SelectById.class);
    public static void main(String[] args) throwsException{
        long startTime =System.currentTimeMillis();
        Reader reader=Resources.getResourceAsReader("mybatis-config.xml");
        SqlSessionFactory ssf=newSqlSessionFactoryBuilder().build(reader);
        reader.close();
        SqlSession session=ssf.openSession();
        try{
            EmpMapper mapper=session.getMapper(EmpMapper.class);
            String ctime="2017-11-01 00:00:01";
            for(int i=0;i<10000;i++) {
                List<Employee> emps=new ArrayList<Employee>();
                for(int j=0;j<1000;j++) {
                    Employee emp=new Employee("E"+i,20,ctime);
                    emps.add(emp);    
                }
                int changed=mapper.batchInsert(emps);
                session.commit();
                System.out.println("#"+i+" changed="+changed);
            }
        }catch(Exception ex) {
            session.rollback();
            logger.error(ex);
        }finally{
            session.close();
            long endTime =System.currentTimeMillis();
            logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + ".");
        }
    }
    //format seconds to day hour minute seconds style
    //Example 5000s will be formatted to 1h23m20s
    public static String toDhmsStyle(longallSeconds) {
        String DateTimes = null;
        long days = allSeconds / (60 * 60 * 24);
        long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60);
        long minutes = (allSeconds % (60 * 60)) / 60;
        long seconds = allSeconds % 60;
        if (days > 0) {
            DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s";
        } else if (hours > 0) {
            DateTimes = hours + "h" + minutes + "m" + seconds + "s";
        } else if (minutes > 0) {
            DateTimes = minutes + "m" + seconds + "s";
        } else{
            DateTimes = seconds + "s";
        }
        returnDateTimes;
    }
}

最后查询数据库,结果如下:

[MyBatis]五分钟向MySql数据库插入一千万条数据 批量插入 用时5分左右第1张

当然插入过程中还有一些插曲,在后继篇章中我会说明。

--END-- 2019年10月12日16:52:14

免责声明:文章转载自《[MyBatis]五分钟向MySql数据库插入一千万条数据 批量插入 用时5分左右》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇前端开发自动换行jdbc与TiDB数据库交互的过程下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

MySQL:参数wait_timeout和interactive_timeout以及空闲超时的实现【转】

一、参数意思 这里简单解释一下两个参数,含义如下: interactive_timeout:The number of seconds the server waits for activity on an interactive connection before closing it. An interactive client is defin...

数据库并发处理

为什么要有锁? 我们都是知道,数据库中锁的设计是解决多用户同时访问共享资源时的并发问题。在访问共享资源时,锁定义了用户访问的规则。根据加锁的范围,MySQL 中的锁可大致分成全局锁,表级锁和行锁三类。在本篇文章中,会依次介绍三种类型的锁。在阅读本篇文章后,应该掌握如下的内容: 为什么要在备份时使用全局锁? 为什么推荐使用 InnoDB 作为引擎进行备份?...

could not initialize proxy no Session

解决方法: 1.不用load方法,使用get方法 2.在web.xml添加 <filter><filter-name>openSessionInView</filter-name><filter-class>org.springframework.orm.hibernate3.support.OpenSess...

Java 字符串常用操作(String类)

字符串查找 String提供了两种查找字符串的方法,即indexOf与lastIndexOf方法。 1、indexOf(String s) 该方法用于返回参数字符串s在指定字符串中首次出现的索引位置,当调用字符串的indexOf()方法时,会从当前字符串的开始位置搜索s的位置;如果没有检索到字符串s,该方法返回-1 1 String str ="We a...

Java Properties 类读取配置文件信息

在我们平时写程序的时候,有些参数是经常改变的,而这种改变不是我们预知的。比如说我们开发了一个操作数据库的模块,在开发的时候我们连接本地的数据库那么IP,数据库名称,表名称,数据库主机等信息是我们本地的,要使得这个操作数据的模块具有通用性,那么以上信息就不能写死在程序里。通常我们的做法是用配置文件来解决。 各种语言都有自己所支持的配置文件类型。比如Pytho...

Mysql大并发热点行更新的两个骚操作

要想db操作的性能足够高,巧妙的设计很重要,事务的操作范围要尽量的小。一般情况下我们都是使用某个orm框架来操作db,这一类框架多数的实现方式都是夸网络多次交互来开启事务上下文和执行sql操作,是个黑盒子,包括对 autocommit 设置的时机也会有一些差异,稍微不注意就会踩坑。 在大并发的情况下加上夸网络多次交互,就不可避免的由于网络延迟、丢包等原因导...