问题描述
我使用Spring MVC 4.0.6和Hibernate 4.3.5。我试图插入值到我的数据库表,但我得到这个错误信息:
$ b
HTTP状态500 - 请求处理失败;嵌套异常是org.hibernate.HibernateException:找不到当前线程的会话
目前我正在使用 sessionFactory。 getCurrentSession()
来保存我的数据,但是如果我使用 getSessionFactory()。openSession();
它可以很好地工作。我听说我应该使用 getCurrentSession
而不是 getSessionFactory()。openSession();
,因为它每创建一个新会话我可以做一个数据库查询。
请看下面的代码,告诉我我做错了什么,以及如何获取 sessionFactory.getCurrentSession ()
工作?
GradeServiceImpl:
$ b @Service
@Transactional
public class GradeServiceImpl implements GradeService {
$ b $ @Autowired
Private GradeDao gradeDao;
@Override
public void addGrade(年级){
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);
$ b servlet-context。 xml
<?xml version =1.0encoding =UTF-8?>
< beans:beans xmlns:beans =http://www.springframework.org/schema/beansxmlns =http://www.springframework.org/schema/mvcxmlns:context = http://www.springframework.org/schema/contextxmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexsi: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 //>
< beans:bean class =org.springframework.web.servlet.view.InternalResourceViewResolver>
< beans:property name =prefixvalue =/ WEB-INF / views //>
< beans:property name =suffixvalue =。jsp/>
< / beans:bean>
< beans:bean id =dataSourceclass =org.apache.commons.dbcp2.BasicDataSourcedestroy-method =close>
< beans:property name =driverClassNamevalue =com.mysql.jdbc.Driver/>
< beans:property name =urlvalue =jdbc:mysql:// localhost:3306 / java/>
< beans:property name =usernamevalue =root/>
< beans:property name =passwordvalue =/>
< / beans:bean>
< beans:bean id =messageSourceclass =org.springframework.context.support.ReloadableResourceBundleMessageSource>
< beans:property name =basenamevalue =resources / messages/>
< beans:property name =defaultEncodingvalue =UTF-8/>
< / beans:bean>
< beans:bean id =sessionFactoryclass =org.springframework.orm.hibernate4.LocalSessionFactoryBean>
< beans:property name =dataSourceref =dataSource/>
<! - < beans:property name =configLocation>
< beans:value> classpath:hibernate.cfg.xml< / beans:value>
< / beans:property> - >
< beans:property name =packagesToScanvalue =com.spring/>
< beans:property name =hibernateProperties>
< beans:道具>
< 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:道具>
< / beans:property>
< / beans:bean>
< beans:bean id =transactionManagerclass =org.springframework.orm.hibernate4.HibernateTransactionManager>
< beans:property name =sessionFactoryref =sessionFactory/>
< / beans:bean>
< / beans:beans>
Web.xml
<?xml version =1.0encoding =UTF-8?>
< web-app xmlns =http://java.sun.com/xml/ns/javaeexmlns:xsi =http://www.w3.org/2001/XMLSchema-instance版本=2.5xsi:schemaLocation =http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\">
< context-param>
< param-name> contextConfigLocation< / param-name>
< param-value> /WEB-INF/spring/root-context.xml< / param-value>
< / context-param>
< listener>
< listener-class> org.springframework.web.context.ContextLoaderListener< / listener-class>
< / listener>
< 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>
1< / load-on-startup>
< / servlet>
< servlet-mapping>
< servlet-name> appServlet< / servlet-name>
< url-pattern> /< / url-pattern>
< / servlet-mapping>
< / web-app>
更新 - 堆栈跟踪
exception
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是org.hibernate.HibernateException:找不到当前线程的会话
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)
根本原因
org.hibernate.HibernateException:找不到当前线程的会话
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.GradeService Impl.addGrade(GradeServiceImpl.java:25)
com.spring.org.GradeController.saveGrade(GradeController.java:32)
sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
太阳.reflect.NativeMethodAccessorImpl.invoke(来源不明)
sun.reflect.DelegatingMethodAccessorImpl.invoke(来源不明)
java.lang.reflect.Method.invoke(来源不明)
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.RequestMappingHandlerAd apter.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)
组织。 springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
解决方案您应该删除DAO实现上的@Transactional注释。取而代之的是你的Service方法;
@Override
@Transactional
public void addGrade(Grade grade){
gradeDao.addGrade(grade);
}
只有服务实现需要所有数据库操作的@Transactional。
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:
HTTP Status 500 - Request processing failed; nested exception is 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 getCurrentSession
instead of getSessionFactory().openSession();
because it creates a new session every time I make a database query.
Could you please see my code below and tell me what I am doing wrong and how to get sessionFactory.getCurrentSession()
working ?
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
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)
解决方案 You should remove the @Transactional annotation on your DAO implementation. Instead in your Service method;
@Override
@Transactional
public void addGrade(Grade grade) {
gradeDao.addGrade(grade);
}
Only service implementation required @Transactional for all database operations.
这篇关于获取“找不到当前线程的会话”使用getCurrentSession()时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!