The answers of Burt and Kimble will work, but you can do it more easily. You need to create a class that implements the Hibernate CurrentSessionContext class, but there is no need to create proxies for the factory session, since you can override the session creation behavior in the session context class, and then simply specify the name of this class in the properties of your factory bean session. e.g. write your session context as follows
import org.hibernate.FlushMode; import org.hibernate.classic.Session; import org.hibernate.context.JTASessionContext; import org.hibernate.engine.SessionFactoryImplementor; public class MySessionContext extends JTASessionContext { public MySessionContext(SessionFactoryImplementor factory) { super(factory); } @Override protected Session buildOrObtainSession() { Session session = super.buildOrObtainSession();
Then, in the properties that you pass to your factory session class, specify this class name:
hibernate.current_session_context_class=org.company.MySessionContext
For example, in a typical Spring script, you can use the Spring factory bean to create the properties of your sleep mode, for example:
<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="properties"> <props> <prop key="hibernate.current_session_context_class">org.company.MySessionContext</prop> // your other Hibernate properties here </props> </property> </bean>
Then, as a rule, you will create a factory session using the Spring factory bean session, for example (the name of the package of notes will differ for different versions of Hibernate):
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocations" ref="hibernateConfigLocations"/> <property name="hibernateProperties" ref="hibernateProperties"/> <property name="entityInterceptor" ref="hibernateEntityInterceptor"/> <property name="jtaTransactionManager" ref="transactionManager"/> <property name="implicitNamingStrategy" ref="underscoresNamingStrategy"/> </bean>
Hibernate includes three different session context classes, so just override the value that applies to you:
org.hibernate.context.JTASessionContext org.hibernate.context.ThreadLocalSessionContext org.hibernate.context.ManagedSessionContext
All three have a buildOrObtainSession method, and the javadoc for the method actually says "provided for subclass purposes." A JTA session context will be needed if you use transactions that span multiple resources, such as multiple databases or databases and JMS queues, if you just access one resource in each transaction, then a ThreadLocalSessionContext will be enough.