Alex Rivera | Logout

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

Asked 2009-04-09T15:00:10.347
19

I'm trying to access the current hibernate session in a test case, and getting the following error:

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63) at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:574)

I've clearly missed some sort of setup, but not sure what.

Any help would be greatly appreciated. This is my first crack at Hibernate / Spring etc, and the learning curve is certainly steep!

Code follows:

The offending class:

public class DbUnitUtil extends BaseDALTest {
    @Test
    public void exportDtd() throws Exception
    {

        Session session = sessionFactory.getCurrentSession();

        session.beginTransaction();
        Connection hsqldbConnection = session.connection(); 

        IDatabaseConnection connection = new DatabaseConnection(hsqldbConnection);

        // write DTD file
        FlatDtdDataSet.write(connection.createDataSet(), new FileOutputStream("test.dtd"));
    }
}

Base class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class BaseDALTest extends AbstractJUnit4SpringContextTests {
    public BaseDALTest()
    {
        super();
    }
        @Resource
        protected SessionFactory sessionFactory;
}

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springf
Edit
Report

1 Answer

31

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).

answered 2009-07-18T12:07:45.947

Your Answer