批量插入@Transactional批注 [英] Batch inserts with @Transactional annotation
问题描述
在我的春天应用程序中,我想一次性在数据库中插入近1500条记录。我在后端使用Spring 4.X和普通的hibernate。在我的服务层中,我使用@Transactional注释。现在在插入记录后,我得到了outofmemory错误。在互联网上搜索后,我发现我们可以使用类似于此的内容。
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
(int i = 0; i <100000; i ++){
Customer customer = new Customer(.....);
session.save(customer);
if(i%20 == 0){// 20,与JDBC批量大小相同
//刷新一批插入并释放内存:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
但是,上面的代码他们手动使用sessionFactory和事务并在会话对象上使用flush和clear, ia手动提交。
在我的情况下,我不想使用上面的代码,我想使用@Transactional注释来完成这项工作。
请建议
我不想手动使用会话工厂和交易对象。 .... @ transactional应该全部做到这一点
如果您想从BMT(Bean Managment Transaction)更改为CMT(Container交易管理),你的代码片段将变成:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveCustomers(){
(int i = 0; i <100000; i ++){
Customer customer = new Customer(.....);
session.save(customer);
$ / code>
当方法结束时,容器将刷新所有实体。现在我想问你,为什么你需要每20个实体?
In my spring application i want to insert almost 1500 records in database in one go. I am using Spring 4.X and plain hibernate in backend. In my service layer i use @Transactional annotation. Now while inserting the records after somepoint i get outofmemory error. After searching on internet i found out that we can use something similar to this
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
Customer customer = new Customer(.....);
session.save(customer);
if ( i % 20 == 0 ) { //20, same as the JDBC batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
However, above code they are using sessionFactory and transaction manually and use flush and clear on session object and do i a manual commit.
In my case i do not want to use above code, i want to use @Transactional annotation to make this work.
Please suggest
I do not want to use session factory and transaction object manually. ....@transactional should do it all
If you want change from BMT(Bean Managment Transaction) to CMT (Container Transaction Managment), your snippet on code will became:
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void saveCustomers(){
for ( int i=0; i<100000; i++ ) {
Customer customer = new Customer(.....);
session.save(customer);
}
}
The container will flush all entities when the method will end. Now I want to ask you, Why Do you nees to need each 20 entities?
这篇关于批量插入@Transactional批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!