Spring / Hibernate / JUnit - No Hibernate Session bound to Thread Spring / Hibernate / JUnit - No Hibernate Session bound to Thread spring spring

Spring / Hibernate / JUnit - No Hibernate Session bound to Thread


Wrong, that will just fill your code with session management code.

First, add a transaction management bean in your context:

    <bean id="transactionManager"           class="org.springframework.orm.hibernate3.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory"/>    </bean>

The second thing, extend AbstractTransactionalJUnit4SpringContextTests

    public class BaseDALTest            extends AbstractTransactionalJUnit4SpringContextTests{

Third thing, annotate you test class with

    @TransactionConfiguration    @Transactional

If your transaction demarcation is correct(surrounding your dao or service) you should be done.

It's not nice to sprinkle session and transaction handling code all around your code (even inside your tests).


Please refer to the Spring documentation. There is a whole chapter on testing, and a section on transaction management:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testing-tx

I've had success extending AbstractTransactionalJUnit4SpringContextTests, but there's a workaround:

TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);transactionTemplate.execute(new TransactionCallbackWithoutResult() {    @Override    protected void doInTransactionWithoutResult(TransactionStatus status) {        // DAO has access to the session through sessionFactory.getCurrentSession()        myDao.findSomething(id);    }});


With the above Spring configuration, it should be sufficient to code

Session session = sessionFactory.getCurrentSession();

in your method and class to test. Session management is done by the Hibernate / Spring /JUnit test configuration, as later is done in the Hibernate / Spring configuration in the real application.

This is how it worked for my tests. In the final web application there will automatically be a Hibernate session associated with the current web request and therefore in testing there should be no sessionFactory.openSession() call.