Over a million developers have joined DZone.

How I Resolved SpringMVC+Hibernate Error: No Hibernate Session Bound to Thread

I used the SpringMVC @Controller annotation approach and configured the Web related Spring configuration in dispatcher-servlet.xml.

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

While developing a web application using SpringMVC and Hibernate I got "No Hibernate Session bound to thread Exception" becuase of some configuration issue.

Here I am going to explain how I resolved the issue.

I used the SpringMVC @Controller annotation approach and configured the Web related Spring configuration in dispatcher-servlet.xml as follows:


<beans>    <context:annotation-config"/>    <context:component-scan base-package="com.sivalabs"/>        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"></bean>         <bean id="messageSource"            class="org.springframework.context.support.ResourceBundleMessageSource"            p:basename="Messages"></bean></beans>

I have configured my business serices and DAOs in applicationContext.xml as follows:

<beans>        <context:component-scan base-package="com.sivalabs"/>    <context:property-placeholder location="classpath:app-config.properties"/>        <tx:annotation-driven/>        <bean id="transactionManager"            class="org.springframework.orm.hibernate3.HibernateTransactionManager"            p:sessionFactory-ref="sessionFactory"></bean>        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource"></property>        <property name="mappingResources">          <list>            <value>UserAccount.hbm.xml</value>            <value>Contact.hbm.xml</value>          </list>        </property>        <property name="hibernateProperties">          <props>            <prop key="hibernate.dialect">${hibernate.dialect}</prop>            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>            </props>        </property>      </bean>        <bean     id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        .....        .....    </bean></beans>


To enable the transaction management I have used @Transactional annotation on my business services.


package com.sivalabs.homeautomation.useraccounts;@Service@Transactionalpublic class UserAccountsService{    @Autowired    private UserAccountsDAO userAccountsDAO;        public UserAccount login(Credentials credentials) {        return userAccountsDAO.login(credentials);    }}


But when I invoked UserAccountsService.login() method I got the the below 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:544)    at com.sivalabs.homeautomation.useraccounts.UserAccountsDAO.login(UserAccountsDAO.java:30)    at com.sivalabs.homeautomation.useraccounts.UserAccountsService.login(UserAccountsService.java:25)    at com.sivalabs.homeautomation.useraccounts.LoginController.login(LoginController.java:51)


Here I have enabled the Annotation based configuration using <context:annotation-config/>.

I have configured the base package containing the Spring beans using <context:component-scan base-package="com.sivalabs"/>.

I have enabled the Annotation based Transaction Management using <tx:annotation-driven/> and @Transactional.


But still I am getting "No Hibernate Session bound to thread" Exception. Why?


Here is the reason:


In Spring reference documentation we can found the below mentioned important note:


<tx:annotation-driven/> only looks for @Transactional on beans in the same application context it is defined in. This means that, if you put <tx:annotation-driven/> in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services.


So when my application is started first it loads the beans configured in dispatcher-servlet.xml and then look in applicationContext.xml.

As i mentioned "com.sivalabs" as my base-package to scan for Spring beans my business services and DAOs which are annotated with @Service, @Repository will also be loaded by the container. Later when Spring tries to load beans from applicationContext.xml it won't load my services and DAOs as they are already loaded by parent ApplicaationContext. So the <tx:annotation-driven/> wont be applied for business services or DAOs annotated with @Transactional.


Solution1: If you are following package-by-layer approach:
Probably you may put all your controllers in one package say com.sivalabs.appname.web.controllers

Then change the <context:annotation-config/> configuration in dispatcher-servlet.xml as:

<context:component-scan base-package="com.sivalabs.appname.web.controllers"/>

With this only the controllers annotated with @Controller in com.sivalabs.appname.web.controllers package will be loaded by parent ApplicationContext and rest of the services, DAOs will be loaded by child ApplicationContext.

Solution2: If you are following package-by-feature approach:
If you follow the package-by-feature approach, you will put all the Controller, Service, DAOs related to one feature in one package.
With this the Controllers, Services, DAOs will be spanned across the packages.

Then change the <context:annotation-config/> configuration in dispatcher-servlet.xml as:

<context:component-scan base-package="com.sivalabs" use-default-filters="false">    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>

With this only the controllers annotated with @Controller will be loaded by parent ApplicationContext.
And the Services, DAOs will be loaded by child ApplicationContext and <tx:annotation-driven/> will be applied.

From : http://sivalabs.blogspot.com/2011/05/springmvc-hibernate-error-no-hibernate.html

 

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:
java,sql,hibernate,spring,spring mvc

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}