今天试了两种Hibernate数据批量插入:
一、通过JDBC的API来进行插入
final List<存入的类别> list= ....;
hibernateTemplate.execute(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
int count = 0;
Transaction ts = session.beginTransaction();
int count = 0;
for(Iterator it = list.iterator();it.hasNext();){
session.save(it.next());
count ++;
if(count%50 == 0){
session.flush();
session.clear();
}
}
ts.commit();
session.close();
return null;
}
});
二、路过Hibernate直接通过JDBC来插入
final List<Student> studentList = ...;
hibernateTemplate.execute(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Connection conn = session.connection();
PreparedStatement pst = null;
String sql = "insert into inf_student (id,name,sex,code) values(?,?,?,?)";
pst=conn.prepareStatement(sql);
UUIDHexGenerator uuidGenerator = null;
int num = studentList.size();
while(num>count){
for(int i=num;i>(num-count);i--){
Student student = (Student)studentList.get(i-1);
uuidGenerator = new UUIDHexGenerator();
pst.setString(1, uuidGenerator.generate(null, null).toString());
pst.setString(2, student.getName());
pst.setString(3, student.getSex());
pst.setString(4, student.getCode());
pst.addBatch();
}
pst.executeBatch();
session.flush();
num -= count;
}
if(num>0){
for(int i=0;i<num;i++){
InfStudent student = (InfStudent)studentList.get(i);
uuidGenerator = new UUIDHexGenerator();
pst.setString(1, uuidGenerator.generate(null, null).toString());
pst.setString(2, student.getName());
pst.setString(3, student.getSex());
pst.setString(4, student.getCode());
pst.addBatch();
}
}
pst.executeBatch();
session.flush();
session.clear();
return null;
}
});
在数据量较大时,第二种方法比第一种要有较明显的优势,但是第二种写起来要复杂一些,尤其是要插入字段较多时inser 语句sql 和pst Set写起来很麻烦
本文对比了两种Hibernate数据批量插入方法:一种是通过Hibernate API,另一种是直接使用JDBC进行操作。在大数据量的情况下,直接使用JDBC的方法表现更优。
954

被折叠的 条评论
为什么被折叠?



