Getting a No Session for Current Thread exception when using getCurrentSession ()

I am using Spring MVC 4.0.6 and Hibernate 4.3.5. I am trying to insert values ​​into my database table, but I am getting this error message:

HTTP status 500 - request processing failed; The nested exception is org.hibernate.HibernateException: session not found for the current thread

I am currently using sessionFactory.getCurrentSession()to save my data, but if I use getSessionFactory().openSession();, it works great. I heard that I should use getCurrentSessioninstead getSessionFactory().openSession();, because it creates a new session every time I make a database query.

Could you see my code below and tell me what I am doing wrong, and how to get the sessionFactory.getCurrentSession()job?

GradeServiceImpl:

@Service
@Transactional
public class GradeServiceImpl implements GradeService {

 @Autowired
 private GradeDao gradeDao;

 @Override
 public void addGrade(Grade grade) {

    gradeDao.addGrade(grade);
 }
}

Gradedaoimpl

@Repository
@Transactional
public class GradeDaoImpl implements GradeDao {

 @Autowired
 private SessionFactory sessionFactory;

 public SessionFactory getSessionFactory() {
    return sessionFactory;
 }

 public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
 }
 @Override
 public void addGrade(Grade grade) {

    sessionFactory.getCurrentSession().save(grade);

 }
}  

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

   <annotation-driven />
   <context:annotation-config />
   <context:component-scan base-package="com.spring" />


   <resources mapping="/resources/**" location="/resources/" />
   <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
   <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <beans:property name="prefix" value="/WEB-INF/views/" />
      <beans:property name="suffix" value=".jsp" />
   </beans:bean>

   <beans:bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
      <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <beans:property name="url" value="jdbc:mysql://localhost:3306/java" />
      <beans:property name="username" value="root" />
      <beans:property name="password" value="" />
   </beans:bean>

   <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
      <beans:property name="basename" value="resources/messages" />
      <beans:property name="defaultEncoding" value="UTF-8" />
   </beans:bean>

   <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <beans:property name="dataSource" ref="dataSource" />
      <!-- <beans:property name="configLocation">
        <beans:value>classpath:hibernate.cfg.xml</beans:value>
        </beans:property>    -->
      <beans:property name="packagesToScan" value="com.spring" />
      <beans:property name="hibernateProperties">
         <beans:props>
            <beans:prop key="dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
            <beans:prop key="show_sql">true</beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
         </beans:props>
      </beans:property>
   </beans:bean>

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

</beans:beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/root-context.xml</param-value>
   </context-param>
   <!-- Creates the Spring Container shared by all Servlets and Filters -->
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <!-- Processes application requests -->
   <servlet>
      <servlet-name>appServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>appServlet</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

Update - stack trace

exceptions

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

root of cause

org.hibernate.HibernateException: No Session found for current thread
    org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
    org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
    com.spring.org.dao.GradeDaoImpl.addGrade(GradeDaoImpl.java:33)
    com.spring.org.service.GradeServiceImpl.addGrade(GradeServiceImpl.java:25)
    com.spring.org.GradeController.saveGrade(GradeController.java:32)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
+1
source share
6 answers

in the sleep mode properties, add this line.

 <beans:prop key="hibernate.current_session_context_class">thread</beans:prop>

so your hibernateProperties looks like this:

  <beans:property name="hibernateProperties">
     <beans:props>
        <beans:prop key="dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
        <beans:prop key="show_sql">true</beans:prop>
        <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
        //add this
        <beans:prop key="hibernate.current_session_context_class">thread</beans:prop>
        <beans:prop key="hibernate.show_sql">true</beans:prop>
     </beans:props>

you need to open a transaction. So do it.

public void addGrade(Grade grade) {

    Session session = sessionFactory.getCurrentSession()
     Transaction tx = null;
     try{
     tx = session.beginTransaction();
     session.save(grade);   
     tx.commit();
       }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
     }

}

+1
source

I had the same problem.

I used annotation-based customization, I configured sessionfactory, datasource and transaction manager for everything. but I did not submit the @EnableTransactionManagement annotation in the AppConfig class.

After adding the transaction annotation, the code is as follows.

@Configuration
@ComponentScan("com.bmp.*")
@EnableWebMvc
@PropertySource("classpath:${env}.properties")
@EnableTransactionManagement
public class AppConfig {
-----
}

The above annotations resolved my issue.

, , , .

+1

@Transactional DAO. ""

@Override
@Transactional
public void addGrade(Grade grade) {
    gradeDao.addGrade(grade);
}

@Transactional .

+1

Narmer, servlet-context.xml, root-context.xml. ( ) , , stacktrace: GradeController.saveGrade GradeServiceImpl.addGrade, GradeDaoImpl.addGrade.

@Transactional , dao- ( ). ,

@Autowired
private GradeService gradeService;

, stacktrace .

:

: <tx:annotation-driven/>, spring @Transactional.

0

:

sessionFactory.getCurrentSession() sessionFactory.openSession(), hibernate , ( , getCurrentSession() factory).

, , , . , hibernateProperties:

<beans:prop key="hibernate.current_session_context_class">thread</beans:prop>

The reason sessionFactory.openSession()works fine, but above hibernate, the hibernate property is not looking for context-sensitive applications session, it needs to create a new instance of the session every time you call openSession()on sessionFactory.

Hope this helps you.

0
source

try using an older version of spring ... Im using spring 3.2.8.RELEASE with hibernate 4.2.11.Final ...

-2
source

Source: https://habr.com/ru/post/1606121/


All Articles