java 我应该经常调用 EntityManager.clear() 以避免内存泄漏吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2243554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Am I supposed to call EntityManager.clear() often to avoid memory leaks?
提问by RubenLaguna
I'm new to JPA/OpenJPA and I noticed that if I don't call EntityManager.clear()after i persist entities I get an OutOfMemoryError(I keep adding new entities in a loop). I'm not sure if this is the expected behavior or it's just and OpenJPA 1.2.1 glitch.
我是 JPA/OpenJPA 的新手,我注意到如果我EntityManager.clear()在持久化实体后不调用,我会得到一个OutOfMemoryError(我不断在循环中添加新实体)。我不确定这是否是预期的行为,或者只是 OpenJPA 1.2.1 的故障。
So, am I required to explicitly detach the entities myself? If I'm not, it's a good practice anyway?
那么,我是否需要自己明确分离实体?如果我不是,无论如何这是一个好习惯?
采纳答案by Padmarag
I don't have much experience with JPA. However this'll be useful -
In JPA you must either:
- Create a new EntityManager for each transaction.
- Call clear() after each transaction to clear the persistence context.
我对 JPA 没有太多经验。但是这会很有用 -
在 JPA 中,您必须:
- 为每个事务创建一个新的 EntityManager。
- 在每个事务之后调用 clear() 以清除持久性上下文。
回答by DataNucleus
Depends how many objects you bring into the persistence process (read). If you handle large numbers (or some of the objects are large) then use of clear() can make sense. Each time an object is read it should be put in the L1 cache by the JPA impl.
取决于您将多少对象带入持久性过程(读取)。如果您处理大量(或某些对象很大),那么使用 clear() 是有意义的。每次读取对象时,JPA impl 都应将其放入 L1 缓存中。
回答by Adeel Ansari
It sounds like there is something wrong somewhere, in your design. Usually, the entity gets detached once it is outside the scope of entity manager. And thats one of the reason you can't lazy load relations, outside the scope.
听起来您的设计中某处有问题。通常,实体一旦超出实体管理器的范围就会分离。这就是您不能在范围之外延迟加载关系的原因之一。
As far as my experience is concerned, I seldom used em.clear(), if ever. I used Hibernate implementation, and Toplink Essentials. No experience with OpenJPA, yet.
就我的经验而言,我很少使用 em.clear(),如果有的话。我使用了 Hibernate 实现和 Toplink Essentials。还没有使用 OpenJPA 的经验。

