Long winded explanation of question commences:
There is a popular
pattern when using Hibernate within a web application where a filter is used to open a hibernate session when a request has begun and closes it when the request ends.
I would like to be able to do something similar with my Stateless session beans. However, what I would like to be able to do is listen for when the CMT Transaction ends and close the hibernate session then. So, it would go something like this:
1. A transaction is begun when a stateless session bean method is called (the transaction setting is 'Required'). This may or may not be the bean that makes use of Hibernate.
2. A SLSB method that uses Hibernate checks a ThreadLocal to see if a hibernate session exists on this
thread. If not, it creates the session, and also registers some kind of listener on the container-provided JTA transaction via the Synchronization interface (presumbaly). Note that I said Synchronization...not SessionSynchronization. I can't use SessionSynchronization because this is a SLSB.
3. The method does its database work using Hibernate.
4. The method ends. This does not necessarily mean the transaction ends, so I don't necessarily want to have the hibernate session closed yet. I may want to use the same hibernate session again within the same transaction but from another method call or SLSB.
5. The transaction ends. At this time, my listener is informed and I close the Hibernate session, thus committing any database changes. I also remove the Hibernate session from the ThreadLocal.
I know that this is possible, because Spring does it (or something very similar). However, I am unable to use Spring for political reasons within my company. So I need to make a home grown solution.
The part that I haven't figured out yet is how to attach a listener to the CMT (JTA) Transaction. I think I can do this within a SLSB method:
TransactionManager mgr =
(TransactionManager)sessionCtx.getUserTransaction();
Transaction tran = mgr.getTransaction();
tran.registerSynchronization(myImplementationOfSynchronization);
But is it okay to assume that the UserTransaction returned from the SessionContext can be cast to a TransactionManager?
Is there a better way to do what I want? I've done a lot of searching without success for an answer...
Thanks!
[ August 11, 2005: Message edited by: Jeff Wisard ]