一: hibernate的批量插入操作:
hibernate进行批量插入时候,调用jdbc的批量插入效率要远高于hibernate的批量插入;
1 通过hibernate调用jdbc API完成100000条数据插入:
package com.tem.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.SessionFactoryImplementor;
import com.tem.hib.Classes;
public class Test {
public static void main(String[] args) {
long ls=System.currentTimeMillis();
Configuration cfg=new AnnotationConfiguration().configure();
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
session.beginTransaction();
try {
Connection conn=((SessionFactoryImplementor)session.getSessionFactory()).getConnectionProvider().getConnection();
String sql="insert into classes c values(?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
for(int i=5;i<100005;i++){
ps.setInt(1, i);
ps.setString(2, "C"+i);
ps.addBatch();
}
ps.executeBatch();
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.getTransaction().commit();
session.close();
long le=System.currentTimeMillis();
System.out.println(le-ls);
}
}
使用jdbc API执行时间为1000多毫秒;
使用hibernate api执行插入100000条数据:
package com.tem.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.SessionFactoryImplementor;
import com.tem.hib.Classes;
public class Test {
public static void main(String[] args) {
long ls=System.currentTimeMillis();
Configuration cfg=new AnnotationConfiguration().configure();
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
session.beginTransaction();
for(int i=5;i<100005;i++){
Classes c=new Classes();
c.setCid(i);
c.setCname("c"+i);
session.save(c);
if(i%50==0){
session.flush();
session.clear();
}
}
session.getTransaction().commit();
session.close();
long le=System.currentTimeMillis();
System.out.println(le-ls);
}
}
hibernate API执行完是5000多毫秒;
所以批量插入时候,尽量通过hibernate调用jdbcqpi来完成插入操作;
二: 修改和删除,可以通过HQL语句加条件完成批量操作;