0

I am getting a "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" with Spring 3.2 with Hibernate 3.3

DAO class :

@Repository
public class ContactDAOImpl implements ContactDAO {
    @Autowired
    private SessionFactory sessionFactory;
    public List<Contact> listContact() {
        return sessionFactory.getCurrentSession().createQuery("from Contact").list();
    }
 ......
   }
}

Context configuration:

<beans .....>
    <context:annotation-config />
    <context:component-scan base-package="org.spring.*" />
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        .......
    </bean>
<!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>
        <property name="annotatedClasses">
        <list>
           <value>org.spring.entity.Contact</value>
        </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
   </bean>

Although I have defined TransactionManager,I do not use it anywhere.
Why am I getting the above error - when no place within my code uses or defines transactions?
Why am I forced to define a transaction?

IUnknown
  • 9,301
  • 15
  • 50
  • 76
  • possible duplicate of [No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here](http://stackoverflow.com/questions/3289979/no-hibernate-session-bound-to-thread-and-configuration-does-not-allow-creation) – chrylis -cautiouslyoptimistic- Aug 15 '13 at 03:20

1 Answers1

0

How are you calling your DAO method? it needs to be called within a transaction, ideally from a service layer, the service can then be called by a controller for example. Note the @Transactional annotation at the method in the service class.

@Service
public class ContactServiceImpl implements ContactService {
    @Autowired
    private ContactDAO contactDAO;

    @Transactional
    public List<Contact> listContact() {
        return contactDAO.listContact();
    }
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325
Taoufik Mohdit
  • 1,910
  • 3
  • 26
  • 39