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.