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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services

Trending

  • LTS JDK 21 Features
  • How to Submit a Post to DZone
  • Spring Authentication With MetaMask
  • Docker and Kubernetes Transforming Modern Deployment
  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.

Siva Prasad Reddy Katamreddy user avatar by
Siva Prasad Reddy Katamreddy
·
May. 18, 11 · Tutorial
Like (2)
Save
Tweet
Share
68.51K 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

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: