一、即便分批次用mybatis插入数据,效率依旧不高,原因:
MyBatis一次性批量插入几千条数据,为什么性能很差?-腾讯云开发者社区-腾讯云
文中提出:
默认执行器类型为Simple,会为每个语句创建一个新的预处理语句,也就是创建一个PreparedStatement对象。在我们的项目中,会不停地使用批量插入这个方法,而因为MyBatis对于含有的语句,无法采用缓存,那么在每次调用方法时,都会重新解析sql语句。
从资料可知,耗时就耗在,由于我foreach后有5000+个values,所以这个PreparedStatement特别长,包含了很多占位符,对于占位符和参数的映射尤其耗时。并且,查阅相关资料可知,values的增长与所需的解析时间,是呈指数型增长的。
并且文中总结用mybatis需要将每次插入的记录控制在 20~50 左右。
但是经本人测试,value数量为500、1000、1500、2000、2500 ... 10000,发现500时,每条数据插入时间为0.1秒左右,10000时,每条数据插入时间0.013秒左右,并未像作者提出的那样,具体情况不得而知。
最后,还是建议用JDBC,因为真的很快 QAQ
二、批量插入数据效率对比,不同场景所用方案:
Mybatis与JDBC批量插入MySQL数据库性能测试及解决方案 - 竹马今安在 - 博客园
三、JDBC批量插入数据
Connection conn = null;PreparedStatement pstm =null;ResultSet rt = null;String host = System.getenv("DATA_MYSQL_HOST");String port = System.getenv("DATA_MYSQL_PORT");String database = System.getenv("DATA_MYSQL_DATABASE");//rewriteBatchedStatements=true 开启批量处理String url = String.format("jdbc:mysql://%s:%s/%s?rewriteBatchedStatements=true", host, port, database);String user = System.getenv("DATA_MYSQL_USER");String password = System.getenv("DATA_MYSQL_PASSWORD");try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection(url, user, password);String sql = "INSERT INTO t_table(name, create_data, value) VALUES(?,?,?)";pstm = conn.prepareStatement(sql);conn.setAutoCommit(false);//计算插入时间Long startTime = System.currentTimeMillis();for (int i = 0; i < tables.size(); i++) {Point point = points.get(i);pstm.setString(1, point.getName());pstm.setTimestamp(2, new Timestamp(point.getCreateDate().getTime()));pstm.setBigDecimal(3, point.getValue());pstm.addBatch();}pstm.executeBatch();conn.commit();Long endTime = System.currentTimeMillis();System.out.println("OK,用时:" + (endTime - startTime));} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);} finally{if (pstm != null) {try {pstm.close();} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}}}
参考:JDBC实现往MySQL插入百万级数据 - 酒香逢 - 博客园