java 使用 getCurrentSession() 时出现“No Session found for current thread”异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25937477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:59:28  来源:igfitidea点击:

Getting "No Session found for current thread" exception when using getCurrentSession()

javaspringhibernate

提问by black_belt

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

我正在使用 Spring MVC 4.0.6 和 Hibernate 4.3.5 。我正在尝试向我的数据库表中插入值,但收到此错误消息:

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread

HTTP 状态 500 - 请求处理失败;嵌套异常是 org.hibernate.HibernateException: No Session found for current thread

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

目前我正在使用sessionFactory.getCurrentSession()来保存我的数据,但如果我使用getSessionFactory().openSession();它就可以完美运行。我听说我应该使用getCurrentSession而不是getSessionFactory().openSession();因为每次我进行数据库查询时它都会创建一个新会话。

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

你能不能看看我下面的代码并告诉我我做错了什么以及如何开始sessionFactory.getCurrentSession()工作?

GradeServiceImpl:

GradeServiceImpl:

@Service
@Transactional
public class GradeServiceImpl implements GradeService {

 @Autowired
 private GradeDao gradeDao;

 @Override
 public void addGrade(Grade grade) {

    gradeDao.addGrade(grade);
 }
}

GradeDaoImpl

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

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

<?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

更新 - 堆栈跟踪

exception

例外

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 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)

回答by Killer

in your hibernate properties, add this line.

在您的休眠属性中,添加这一行。

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

so your hibernateProperties looks like this,

所以你的 hibernateProperties 看起来像这样,

  <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 like this.

你需要打开一个交易。所以这样做。

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(); 
      }
     }

}

}

回答by Anil

I had the same problem.

我有同样的问题。

I was using annotation based configuration, I have configured sessionfactory, datasource and transaction manager every thing. but I did not give @EnableTransactionManagement annotation at AppConfig class.

我使用的是基于注解的配置,我已经配置了 sessionfactory、datasource 和 transaction manager。但我没有在 AppConfig 类中给出 @EnableTransactionManagement 注释。

The code looks like below after adding the transaction annotation.

添加事务注释后的代码如下所示。

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

The above annotations resolved my problem.

以上注释解决了我的问题。

Please vote up if this solves your problem, so that it will be helpful for others.

如果这解决了您的问题,请投票,以便对其他人有所帮助。

回答by SPACE _PRO

You should remove the @Transactional annotation on your DAO implementation. Instead in your Service method;

您应该删除 DAO 实现上的 @Transactional 注释。而是在您的 Service 方法中;

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

Only service implementation required @Transactional for all database operations.

对于所有数据库操作,只有服务实现需要 @Transactional。

回答by Serge Ballesta

As stated by Narmer, you put all your database configuration in servlet-context.xmlwhen it should go in root-context.xml. But the real cause of the problem (or a symptom of it) is that you use no transactional proxy as it can be seen in stacktrace : GradeController.saveGradedirectly calls GradeServiceImpl.addGradethat in turn directly calls GradeDaoImpl.addGrade.

正如 Narmer 所说,您将所有数据库配置放入servlet-context.xml应放入的root-context.xml. 但问题的真正原因(或它的症状)是您没有使用事务代理,正如在 stacktrace 中看到的那样:GradeController.saveGrade直接调用GradeServiceImpl.addGrade它,然后直接调用GradeDaoImpl.addGrade.

Normally, you should put the @Transactionalannotation only in service layer, and not in dao layer (only one transactional layer). And you should verify that you autowire the service from the controller as

正常情况下,@Transactional注解应该只放在服务层,不能放在dao层(只有一个事务层)。并且您应该验证您是否将控制器中的服务自动装配为

@Autowired
private GradeService gradeService;

Please try to use only one transactional layer and say if stacktrace shows a transactional proxy usage.

请尝试仅使用一个事务层,并说明 stacktrace 是否显示事务代理使用情况。

Edit :

编辑 :

There is another problem in your config : you have no <tx:annotation-driven/>tag, when it is necessary for spring to correctly process @Transactionalannotations.

您的配置中还有另一个问题:<tx:annotation-driven/>当 spring 需要正确处理@Transactional注释时,您没有标签。

回答by Darshan Lila

Here's whats happening:

这是发生了什么:

When you use sessionFactory.getCurrentSession()instead of sessionFactory.openSession()hibernate would look for a session instance bound to application context thread (in other words a single session instance would be managed by hibernate and returned when getCurrentSession() is called on session factory) .

当您使用sessionFactory.getCurrentSession()而不是sessionFactory.openSession()hibernate 时,将查找绑定到应用程序上下文线程的会话实例(换句话说,单个会话实例将由 hibernate 管理并在会话工厂调用 getCurrentSession() 时返回)。

Now to configure a session bound to application context thread you must specify it in hibernate properties. You can do it by adding following property to hibernateProperties:

现在要配置绑定到应用程序上下文线程的会话,您必须在休眠属性中指定它。您可以通过将以下属性添加到hibernateProperties

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

The reason sessionFactory.openSession()works fine without above hibernate property is hibernate does not look for a sessionbound to application context, it needs to create a new session instance everytime you call openSession()on sessionFactory.

之所以sessionFactory.openSession()能正常工作而不上述Hibernate属性是Hibernate不找一个session绑定到应用程序上下文,它需要创建一个新的会话实例每次你打电话openSession()sessionFactory

Hope this helps you.

希望这对你有帮助。

回答by LetItRock

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

尝试使用旧版本的 spring ......我使用 spring 3.2.8.RELEASE 和 hibernate 4.2.11.Final ......