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

相对于批量插入,这种方式可谓虚耗时光。

代码:

package com.hy.action;

import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import com.hy.entity.Employee;
import com.hy.mapper.EmpMapper;

public class SingleInsert1003 {
private static Logger logger = Logger.getLogger(SelectById.class);

    public static void main(String[] args) throws Exception{
        long startTime = System.currentTimeMillis();

        Reader reader=Resources.getResourceAsReader("mybatis-config.xml");

        SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(reader);
        reader.close();

        SqlSession session=ssf.openSession();

        try {
            EmpMapper mapper=session.getMapper(EmpMapper.class);
            String ctime="2017-11-01 00:00:01";
            int index=0;
            int changedTotal=0;

            for(int i=0;i<10000;i++) {

                for(int j=0;j<1000;j++) {
                    index++;

                    Employee emp=new Employee("E"+String.valueOf(index),index % 100,ctime);
                    int changed=mapper.singleInsert(emp.getName(), emp.getAge(), emp.getCtime());
                    changedTotal+=changed;

                    ctime=timePastOneSecond(ctime);
                }

                session.commit();
                System.out.println("#"+i+" changed="+changedTotal);

            }
        }catch(Exception ex) {
            session.rollback();
            logger.error(ex);
        }finally {
            session.close();

            long endTime = System.currentTimeMillis();
            logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + ".");
        }
    }

    public static String timePastOneSecond(String otime) {
        try {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt=sdf.parse(otime);

            Calendar newTime = Calendar.getInstance();
            newTime.setTime(dt);
            newTime.add(Calendar.SECOND,1);

            Date dt1=newTime.getTime();
            String retval = sdf.format(dt1);

            return retval;
        }
        catch(Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    // format seconds to day hour minute seconds style
    // Example 5000s will be formatted to 1h23m20s
    public static String toDhmsStyle(long allSeconds) {
        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";
        }

        return DateTimes;
    }
}

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>

    <insert id="singleInsert">
        insert into emp(name,age,cdate)
        values (#{name},#{age},#{ctime,jdbcType=TIMESTAMP})
    </insert>
</mapper>

与Mapper对应的接口:

package com.hy.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.hy.entity.Employee;

public interface EmpMapper {
    Employee selectById(long id);
    int batchInsert(List<Employee> emps);
    // 用@Param标签指明和SQL的参数对应能避免出现org.apache.ibatis.binding.BindingException异常
    int singleInsert(@Param("name")String name,@Param("age")int age,@Param("ctime")String ctime);
}

部分输出如下:

#9991 changed=9992000
#9992 changed=9993000
#9993 changed=9994000
#9994 changed=9995000
#9995 changed=9996000
#9996 changed=9997000
#9997 changed=9998000
#9998 changed=9999000
#9999 changed=10000000
 INFO [main] - Time elapsed:1h16m30s.

数据库截图如下:

--END-- 2019年10月12日20:03:26

【Mybatis】向MySql数据库插入千万记录 单条插入方式,用时 1h16m30s的更多相关文章

  1. mybatis连接mysql数据库插入中文乱码

    对于MySQL数据库的乱码问题,有两种情况: 1. mysql数据库编码问题(建库时设定). 2. 连接mysql数据库的url编码设置问题. 对于第一个问题,目前个人发现只能通过重新建库解决,建库的 ...

  2. Spring Boot入门(六):使用MyBatis访问MySql数据库(注解方式)

    本系列博客记录自己学习Spring Boot的历程,如帮助到你,不胜荣幸,如有错误,欢迎指正! 本篇博客我们讲解下在Spring Boot中使用MyBatis访问MySql数据库的简单用法. 1.前期 ...

  3. 五、使用druid管理数据库,mybatis连接mysql数据库

    简介:    使用 mybatis 连接 mysql 数据库, 一套简单的增删改查流程, 前台用 bootstrap, bootstrap-table 框架, 最后用 druid 监控数据库连接情况 ...

  4. (45). Spring Boot MyBatis连接Mysql数据库【从零开始学Spring Boot】

    大家在开发的时候,会喜欢jdbcTemplate操作数据库,有喜欢JPA操作数据库的,有喜欢MyBatis操作数据库的,对于这些我个人觉得哪个使用顺手就使用哪个就好了,并没有一定要使用哪个,个人在实际 ...

  5. mybatis连接mysql数据库实现的jdbc功能

    最近公司项目要使用myBatis,自己以前没有接触过,就在网上找到了一些资料研究了些.初步做出了基于myBatis连接mysql数据库的jdbc实现的功能. employee.java package ...

  6. Mybatis连接mysql数据库出现乱码

    对于mysql数据库的乱码问题,有两中情况: 1. mysql数据库编码问题(建库时设定). 2. 连接mysql数据库的url编码设置问题. 对于第一个问题,目前个人发现只能通过重新建库解决,建库的 ...

  7. mybatis查询mysql数据库tinyint(1)变为boolean类型

    mybatis查询mysql数据库对象转化为Map,tinyint(1)被转化为boolean类型,可以t通过避免使用tinyint(1)来解决.

  8. 如何用IDEA创建springboot(maven)并且整合mybatis连接mysql数据库和遇到的问题

    一.New->Project 二.点击next 三.在Group栏输入组织名,Artifact就是项目名.选择需要的java版本,点击next 四.添加需要的依赖 在这里我们也可以添加sql方面 ...

  9. CentOS6.7下使用非root用户(普通用户)编译安装与配置mysql数据库并使用shell脚本定时任务方式实现mysql数据库服务随机自动启动

    CentOS6.7下使用非root用户(普通用户)编译安装与配置mysql数据库并使用shell脚本定时任务方式实现mysql数据库服务随机自动启动1.关于mysql?MySQL是一个关系型数据库管理 ...

随机推荐

  1. 聚类算法之MeanShift

    机器学习的研究方向主要分为三大类:聚类,分类与回归. MeanShift作为聚类方法之一,在视觉领域有着广泛的应用,尤其是作为深度学习回归后的后处理模块而存在着. 接下来,我们先介绍下基本功能流程,然 ...

  2. (一)Android jni打印到logcat

    #include <stdio.h> #include <android/log.h> int main(void) { int a = 0x10,b = 0x20; __an ...

  3. GOLANG文件拷贝

    GOLANG文件拷贝 在Golang中,使用系统自带函数io.Copy() 如: srcFile := "C:/Users/Wisdom/Desktop/Wisdompic.png" ...

  4. 04_ Flume采集文件到HDFS案例

    采集需求:比如业务系统使用log4j生成的日志,日志内容不断增加,需要把追加到日志文件中的数据实时采集到hdfs 根据需求,首先定义以下3大要素 采集源,即source——监控文件内容更新 :  ex ...

  5. Python 爬虫实现天气查询(可视化界面版)

    github项目地址:StarMan Python 实现天气查询的程序早已完成,近日开学无课,昨晚心血来潮想做一个较为友好的界面版本,便匆忙行动了起来. 在之前已有的程序的基础上使用Tkinter 模 ...

  6. CSS基础学习 21.CSS居中总结

    注意:*在IE中并不代表通配符的意思,是代表根元素的意思,所以为了匹配适应各种浏览器,进行页面初始化 <style> *{ margin:0; padding:0; } </styl ...

  7. 18-SQLServer中给视图创建索引

    一.注意点 1.索引视图所引用的基表必须在同一个数据库中,不是用union all引用多个数据库的表: 2.创建索引视图时要加上with schemabinding: 3.创建索引视图时要指定表所属的 ...

  8. 关于STM32的I2C硬件DMA实现

    关于STM32的I2C硬件DMA实现 网上看到很多说STM32的I2C很难用,但我觉得还是理解上的问题,STM32的I2C确实很复杂,但只要基础牢靠,并没有想象中的那么困难. 那么就先从基础说起,只说 ...

  9. [jenkins] 启动错误 Failed to start LSB: Jenkins Automation Server.

    解决办法见https://blog.csdn.net/qq_34208844/article/details/87865672

  10. .net core 反编译一小段

    public static class A { private static readonly MethodInfo GetServiceInfo; public static IApplicatio ...