如何使用 hibernate 和 spring DAO 模式在数据库中插入批量数据
How to insert bulk data in database using hibernate and spring DAO pattern
我正在开发一个使用 Spring DAO + hibernate 结构来处理数据库的应用程序。
我想使用 hibernate 在 oracle 数据库中插入大量行(大约 20000 行),但是使用 .save() 非常慢。
我了解到使用无状态会话可以做到这一点,但是因为所有会话都是通过 BaseDaoImp 管理的class,我不知道如何在这种设计模式中创建无状态会话。
如果有人知道如何实现这个,请帮忙。
在每第 n 次调用 save()
方法后添加 entityManager.flush()
和 entityManager.clear()
。
如果您使用休眠,则添加 hibernate.jdbc.batch_size
并将其设置为等于 n。 100 个可能就够了,但这是您的选择。
见:
Massive insert with JPA + Hibernate or http://frightanic.com/software-development/jpa-batch-inserts/
答案很旧,但看起来工作正常。
试试这个代码片段,它类似于我们在 JDBC 批处理中使用的方法..
public Long save(HttpServletRequest request) {
**//Further business logic here....**
for ( int i=0; i<count; i++ ) {
getEntityManager().persist((ABC) model);
if ( i > 0 && i % 2500== 0 ) {
getEntityManager().flush();
getEntityManager().clear();
}
}
tx.commit();
((EntityManager) session).close();
}
我正在开发一个使用 Spring DAO + hibernate 结构来处理数据库的应用程序。
我想使用 hibernate 在 oracle 数据库中插入大量行(大约 20000 行),但是使用 .save() 非常慢。
我了解到使用无状态会话可以做到这一点,但是因为所有会话都是通过 BaseDaoImp 管理的class,我不知道如何在这种设计模式中创建无状态会话。
如果有人知道如何实现这个,请帮忙。
在每第 n 次调用 save()
方法后添加 entityManager.flush()
和 entityManager.clear()
。
如果您使用休眠,则添加 hibernate.jdbc.batch_size
并将其设置为等于 n。 100 个可能就够了,但这是您的选择。
见: Massive insert with JPA + Hibernate or http://frightanic.com/software-development/jpa-batch-inserts/
答案很旧,但看起来工作正常。
试试这个代码片段,它类似于我们在 JDBC 批处理中使用的方法..
public Long save(HttpServletRequest request) {
**//Further business logic here....**
for ( int i=0; i<count; i++ ) {
getEntityManager().persist((ABC) model);
if ( i > 0 && i % 2500== 0 ) {
getEntityManager().flush();
getEntityManager().clear();
}
}
tx.commit();
((EntityManager) session).close();
}