Hibernate使用jdbc批量插入
第一种方法:
使用PrepareStatement
//批量导入(jdbc操作)
public void impData(List<Map<String,String>> datalist,TbUser user) throwsSQLException, IOException{
//首先在dao层得到SessionFactory的实例
SessionFactory factory =getSessionFactory();
//通过sessionfactory得到ConnectionProvider
ConnectionProvider provider =((SessionFactoryImpl)factory).getConnectionProvider();
//得到连接对象connection
Connection connection = provider.getConnection();
connection.setAutoCommit(false); //设置为手动提交事务
PreparedStatement ps =connection.prepareStatement("insertinto emp(empName,depId) values(?,?)");
try {
//加入一次插入10000条数据
for (int i = 0; i< 10000; i++) {
ps.setString(1,’hwt’);
ps.setString(2,’123’);
ps.addBatch();
if(i%500==0){//可以设置不同的大小;如50,100,500,1000等等
ps.executeBatch();
connection.commit();
ps.clearBatch();
}
}
ps.executeBatch(); //批量执行
connection.commit();
}catch (Exception e) {
e.printStackTrace();
connection.rollback();
}finally{
ps.close();
connection.close();
}
}
方法二 使用Statement加批量的方法
- conn.setAutoCommit(false);
- Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
- for(int x = 0; x < size; x++){
- stmt.addBatch("INSERT INTO adlogs(ip,website,yyyymmdd,hour,object_id) VALUES('192.168.1.3', 'localhost','20081009',8,'23123')");
- }
- stmt.executeBatch();
- conn.commit();
conn.setAutoCommit(false);
Statement stmt =conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
for(int x = 0; x < size; x++){
stmt.addBatch("INSERT INTOadlogs(ip,website,yyyymmdd,hour,object_id) VALUES('192.168.1.3','localhost','20081009',8,'23123')");
}
stmt.executeBatch();
conn.commit();
方法三:直接使用Statement
- conn.setAutoCommit(false);
- Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- for(int x = 0; x < size; x++){
- stmt.execute("INSERT INTO adlogs(ip,website,yyyymmdd,hour,object_id) VALUES('192.168.1.3', 'localhost','20081009',8,'23123')");
- }
- conn.commit();
conn.setAutoCommit(false);
Statement stmt =conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
for(int x = 0; x < size;x++){
stmt.execute("INSERT INTOadlogs(ip,website,yyyymmdd,hour,object_id) VALUES('192.168.1.3','localhost','20081009',8,'23123')");
}
conn.commit();
使用上述方法分别插入10万条数据的平均测试时间为:
方法一:17.844s
方法二:18.421s
方法三:16.359s