Am I supposed to call EntityManager.clear() often to avoid memory leaks?

RubenLaguna picture RubenLaguna · Feb 11, 2010 · Viewed 19.2k times · Source

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.

So, am I required to explicitly detach the entities myself? If I'm not, it's a good practice anyway?

Answer

Padmarag picture Padmarag · Feb 11, 2010

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.