In the past couple of years we came across a bizarre error on the number of occasions linked to the Hibernate session becoming not available to the thread.
It usually manifests itself with the following exception:
org.springframework.transaction.support.TransactionSynchronizationUtils - TransactionSynchronization.beforeCompletion threw exception
java.lang.IllegalStateException: No value for key [org.hibernate.impl.SessionFactoryImpl@2ea60563] bound to thread [WorkManager(2)-7]
However, from time to time it shows the different message with the similar message which reads that Hibernate session is not available to the current thread.
After some investigation it appears that it is highly likely that this exception occurs when the particular combination of the frameworks involved into the application. We observed it in the J2EE project that is built using combination of Hibernate and Spring running on JBoss 5.1 application server where transaction management is delegated to the JBoss.
It seems that Spring by default wraps the Hibernate's SessionFactory implementation into its own transactional version attached to Spring's transaction support. Since we delegated transaction management to JBoss Hibernate Session will not be bound to the Spring's transaction manager. But Spring's SessionFactoryUtil checks if it is bound to Spring's transaction manager and reports the error if it does not unless it is instructed not to do so.
In order to instruct Spring to ignore the fact that Hibernate session is not bound to the Spring's transaction support the following property should be added to the definition of the Hibernate Session Factory:
<property name="exposeTransactionAwareSessionFactory" value="false"/>
Note that this property makes sense only in case of JTA transaction manager involved and not required when local transaction manager is used.