The way I understand Hibernate, the object really doesn't have a clue that it's being managed, meaning it doesn't really have a handle to its associated session (if there is one). The obvious exception is with proxies and lazy loading...the proxy object has to have a reference to the session in order to perform the lazy load. If by "inject" a session into a persistent object you mean attaching the persistent object to a session, this can be accomplished by calling session.lock( object, LockMode.NONE ) or session.update( object ). This will associate a proxy with the (new?) session and allow lazy loading to occur.
I imagine that you could add a session property to your POJOs and write an interceptor that would set the session property during lifecycle events so that the object has a handle to the session. I don't think that such an approach is recommended, however, as there is a potential to have a handle to the wrong session stored somewhere in one of your POJOs. It might also introduce some interesting side-effects if you are using proxies if you are using those.
The ThreadLocal pattern (HibernateUtil) with a request interceptor (javax.servlet.Filter) has worked well for me and I think is considered a best practice. Rather than associating the session with an object it is associated with the Thread, so your scoping concerns are mitigated.
- Jesse
|