HibernateException No Session found for current thread

HibernateException No Session found for current thread

Exception in thread “main” org.hibernate.HibernateException: No Session found for current thread

Exception in thread "main" org.hibernate.HibernateException: No Session found for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
    at com.javahonk.dao.PersonDAOImpl.save(PersonDAOImpl.java:29)
    at com.javahonk.service.PersonServiceImpl.save(PersonServiceImpl.java:23)
    at com.javahonk.TestHibernate.main(TestHibernate.java:26)

Solution: If you are trying to get sessionFactory.getCurrentSession() without defining your class in transactional scope then you will get above exception because getCurrentSession() can be use only in transactional scope. Please make your class transaction using @Transactional annnotation as shown below example:

@Transactional
public class PersonDAOImpl implements PersonDAO{

And include below tag in your bean.xml file:

<tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

Leave a Reply

Your email address will not be published. Required fields are marked *