views:

789

answers:

4

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?

A: 

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.

Padmarag
Thanks. ok, with the hints in the answers I figured out that I'm not supposed to use just one long-lived EntityManager in the application. I should use method scope or request scope [1]. That would remove the need of calling em.clear(). Thanks![1] http://javanotepad.blogspot.com/2007/08/managing-jpa-entitymanager-lifecycle.html
ecerulm
Useful link. I had used JPA with Dependency Injection (using Seam), so hadn't faced similar issue.
Padmarag
A: 

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.

DataNucleus
A: 

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.

Adeel Ansari
when you say that the entity gets detached one it is outside the scope of entity manager do you mean that I should close the EntityManager and create a new one for each transaction like Padmarag suggests?
ecerulm
A: 

Just a note. Creating an entity manager is an expensive operation. You should try to store it somewhere or inject it.

karel