There is:
Code:
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
try {
...
}
finally {
TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSessionIfNecessary(session, sessionFactory);
}
Of course, you can put the snippet before the try into a TestCase.setUp method, and the stuff in the finally block into a TestCase.tearDown implementation. You just need to use the SessionHolder returned by unbindResource then, as you don't have the session reference available:
Code:
protected void setUp() throws Exception {
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
protected void tearDown() throws Exception {
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSessionIfNecessary(sessionHolder.getSession(), sessionFactory);
}
Note that the above is exactly what OpenSessionInViewFilter is doing internally: Have a look at the source code if you're interested. It simply uses Spring's lower-level transaction and resource management APIs to bind a Session to respectively unbind a Session from the thread, auto-detected there by transaction managers and Hibernate data access code.
Juergen