wood burning stoves 2.0*
The moose likes Object Relational Mapping and the fly likes perform selective clear() in EntityManager Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "perform selective clear() in EntityManager" Watch "perform selective clear() in EntityManager" New topic
Author

perform selective clear() in EntityManager

Carlos Conti
Ranch Hand

Joined: Apr 21, 2010
Posts: 112
Hi there,

I have an application which by the time I started writing it my knowledge in JPA was not as good as today (which is not that much either), and am facing the following problem:

after each persist operation, I call entityManager.clear() in order to detach all entities and keep the manager clear. This helps to solve some errors and not to overload the manager with everything that is read from the database in my application. The point is that I find myself many times where I get many LazyInitializationException's when trying to access dependent collections from entities that have been detached and have not yet been loaded by the application. To get around that what I did was to reattach the needed instance at the very specific code location where the exception occurs to prevent it arising by means of the statement: "entityManager.getInstance(InstanceClass.class, id)". This seems not however a good coding practice and would like to get rid of that.

As an alternative strategy I think I could manually tell the manager which instances need to be kept attached and which not. But don't know how to call or execute a selective clear() call. Is there anyway to iterate over the attached entities and decide wether they need to be detached or not?. The problem is that I cannot detach and reatach, because then I loose the reference grip at critic points of my application such as application instance variables like user or configuration related instances. So the point is that I need to selectively detach entities from the manager.

Any ideas? Any other approaches are greatly appreciated.
Hope the explanation of the problem is clear enough.

Thanks in advance,

Carlos.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: perform selective clear() in EntityManager
 
Similar Threads
Hibernate: merge more than once causes OptimisticLockException
How to obfuscate or mask returned data?
Lazy loading exception in presentation layer, what's the nicest way to avoid them?
Issue when using 2 entity managers to manage one entity from one database to another
Passed SCBCD 5.0 :)