spring-data JPA:手动提交事务并重新启动新事务 [英] spring-data JPA: manual commit transaction and restart new one

查看:45
本文介绍了spring-data JPA:手动提交事务并重新启动新事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种导入数据的方法.如果导入很大,它就无法在单个事务中运行,而不会由于巨大的事务语句缓存而导致 OutOfMemoryError.

I have a method for importing data. In case the import is large it can not run within a single transaction without potentially causing an OutOfMemoryError due to huge transaction statement cache.

我想要的是在语句缓存中的 n 条记录后手动提交.

What I want is to manually commit after n records in statement cache.

我怎样才能做到这一点?(最好在@Transactional 方法中).

How can I achieve this? (preferably within an @Transactional method).

推荐答案

在每 N 次迭代中使用 EntityManager.flush()EntityManager.clear() ,以便会话同步到数据库,并清除 chache 以防止 OOM.

Use EntityManager.flush() and EntityManager.clear() on every Nth iteration, so that the session gets synchronized to the database, and the chache cleared to prevent the OOM.

如果您使用 Hibernate,您还可以将 hibernate.jdbc.batch_size 设置为适当的值,以便在 JDBC 级别进行批处理.

If you use Hibernate, you could also set the hibernate.jdbc.batch_size to an appropriate value to have batching on JDBC level.

如果您还想在批处理后提交并坚持使用@Transactional 方法,那么请重构您的代码,以便@Transactional 方法从输入源获取一批N 条记录,并从外部循环调用该方法.否则,您可以使用 Spring 的 TransactionTemplate 以编程方式控制事务.

If you also want to commit after a batch and insist on a @Transactional method, then refactor your code so that the @Transactional method gets a batch of N records from the input source, and call that method from an external loop. Otherwise you can use Spring's TransactionTemplate to programmatically controll transactions.

这可能有用:http:///docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch15.html

这篇关于spring-data JPA:手动提交事务并重新启动新事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆