DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Querydsl vs. JPA Criteria, Part 6: Upgrade Guide To Spring Boot 3.2 for Spring Data JPA and Querydsl Project
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS

Trending

  • Engineering Closed-Loop Graph-RAG Systems, Part 3: Closing the Loop in Graph-RAG Systems
  • Getting Started With GitHub Copilot CLI for Coding Tasks
  • Detecting Plan Regression in SQL Server Using Query Store
  • How to Interpret the Number of Spring ApplicationContexts in Integration Tests
  1. DZone
  2. Coding
  3. Frameworks
  4. How I Resolved SpringMVC+Hibernate Error: No Hibernate Session Bound to Thread

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.

By 
Siva Prasad Reddy Katamreddy user avatar
Siva Prasad Reddy Katamreddy
·
May. 18, 11 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
69.5K Views

Join the DZone community and get the full member experience.

Join For Free

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

 

Hibernate Session (web analytics) Spring Framework Web Service

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Querydsl vs. JPA Criteria, Part 6: Upgrade Guide To Spring Boot 3.2 for Spring Data JPA and Querydsl Project
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook