我想使用 Hibernate 4.2 将包含 170.000 个实体的列表插入到本地安装的 MySQL 8.0 数据库中。 目前我正在通过 Session#save 方法执行此操作。但插入这么多实体会持续很长时间。那么有没有可能更快地做到这一点?
for (Agagf x : list) {
create(x);
}
// ------------------------
public static void create(Object obj) throws DatabaseException {
Session hsession = null;
try {
hsession = SqlDataHibernateUtil.getSessionFactory().openSession();
Transaction htransaction = hsession.beginTransaction();
hsession.save(obj);
htransaction.commit();
} catch (HibernateException ex) {
throw new DatabaseException(ex);
} finally {
if (hsession != null)
hsession.close();
}
}
最佳答案
Hibernate页面上有这篇文章:http://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch15.html
根据他们的说法,您需要这样的东西:
create(list);
// ------------------------
public static void create(List<Object> objList) throws DatabaseException {
Session hsession = null;
try {
hsession = SqlDataHibernateUtil.getSessionFactory().openSession();
Transaction htransaction = hsession.beginTransaction();
int count = 0;
for(Agagf x: objList) {
hsession.save(obj);
if ( ++count % 20 == 0 ) { //20, same as the JDBC batch size
//flush a batch of inserts and release memory:
hsession.flush();
hsession.clear();
count = 0;
}
}
} catch (HibernateException ex) {
throw new DatabaseException(ex);
} finally {
htransaction.commit();
if (hsession != null) {
hsession.close();
}
}
}
此外,启用批处理的配置:
如果您正在进行批处理,则需要启用 JDBC 批处理。如果您想达到最佳效果,这是绝对必要的 表现。将 JDBC 批处理大小设置为合理的数字(例如 10-50):
hibernate.jdbc.batch_size 20
编辑:根据您的情况,请调整批量大小以更好地适合您的卷。只需记住在配置和用于刷新的 if 语句中设置相同的大小即可。
关于java - 在 Hibernate 中快速插入许多实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56146573/