Wanted to validate with the group a design pattern that I've been using for a little while and appears to work well.
This applies to applications that use JTA, either through wrapping the HttpReuqest with a Transaction [1], Bean Managed
Persistence EJBs or some other kind of middle tier transaction wrapped business logic.
The solution exposes a single getSession() method that can be called anywhere within a Transaction. Let's call it JTASessionFactory.getSession()
The client code that invokes this method, receives the session, uses it and leves it alone, without having to explicitly flush or close.
What happens in getSession() is the following:
1) The first time it is invoked within the scope of the current transaction, a new session is created via SessionFactory.openSession() and a Synchronization listener is attached to the tx.
2) Consequitive calls to getSession() within the scope of the same transaction will return the same session instance.
3) When the transaction is ended (commit or rollback), the synchronization listener flushes and closes the session.
This pattern targets the following benefits:
1) The client code does not have to use repeatedly openSession/try/catch/finally blocks, which are error prone. Just getSession()
2) The session uses one connection from the underlying DataSource pool throughout the duration of a transaction.
3) The session cache is utilized throughout the whole transaction.
4) flush() may not need to be invoked explicitly unless there is specific application need for it like mixing straight JDBC with Hibernate.
5) There is no concern of multiple threads using the same session, because application servers use ThreadLocal to carry a transaction in the same VM.
Let me know if this is a feasible solution.
If it is, I can send the code for CVS.
Ivelin
Resources:
[1] TransactionFilter
http://java.sun.com/blueprints/code/adv ... .java.html