I'm somewhat at a loss about how to actually use a long-running Session in practice.
The problem is with Exceptions: I have no idea how to deal with them without compromising the application's modularity. The normal approach would be: rollback, close Session, create a new Session. Trouble is: Any module in the application might have now-detached objects lying around. They need to be reattached, usually through a merge() in a newly opened Session.
But how do I find out which POJOs are actually entities and need to get merged?
Approach 1: For each object that needs to be merged, have a piece of code that does that. Approach 2: Subclass Session and keep a list of all managed entities. Approach 3: Use an Interceptor and keep a list of all managed entities. Approach 4: Cast Session to SessionImpl and dig through the data structures until you find the first-level object cache. That's the entities that need to be reattached.
None of the above approaches are satisfactory. #1 is inherently unmodular. It's also error-prone since programmers tend to neglect/overlook the exceptional case (I know I do, particularly under deadline pressure). #2 is hard to get right. For example, delete() makes an entity detached, but after rollback, it should be merged anyway because the record has reappeared in the database; the next complication is cascading persists and deletes. Also, duplicating work that Hibernate already does for its internal object cache is disgusting. #3 has essentially the same problems as #2. #4 avoids duplication of work and would probably be easier to get right, but it's prone to breakage as Hibernate evolves.
Does this mean that long-running sessions are a hopeless case? Or did I overlook an approach?
|