我正在使用Spring MVC 4.0.6和Hibernate 4.3.5。我试图将值插入我的数据库表,但我收到此错误消息:
HTTP状态500 - 请求处理失败;嵌套异常是org.hibernate.HibernateException:找不到当前线程的会话
目前我正在使用sessionFactory.getCurrentSession()
来保存我的数据,但如果我使用getSessionFactory().openSession();
则效果很好。我听说我应该使用getCurrentSession
而不是getSessionFactory().openSession();
,因为每次我进行数据库查询时都会创建一个新会话。
请您查看下面的代码并告诉我我做错了什么以及如何让sessionFactory.getCurrentSession()
工作?
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>
例外
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)
根本原因
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)
答案 0 :(得分:1)
在你的hibernate属性中,添加这一行。
<beans:prop key="hibernate.current_session_context_class">thread</beans:prop>
所以你的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>
您需要打开一个交易。 所以这样做。
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 :(得分:1)
我遇到了同样的问题。
我使用的是基于注释的配置,我已经配置了sessionfactory,datasource和事务管理器。但是我没有在AppConfig类中给出@EnableTransactionManagement注释。
添加事务批注后,代码如下所示。
@Configuration
@ComponentScan("com.bmp.*")
@EnableWebMvc
@PropertySource("classpath:${env}.properties")
@EnableTransactionManagement
public class AppConfig {
-----
}
以上注释解决了我的问题。
如果这可以解决您的问题,请立即投票,以便对其他人有所帮助。
答案 2 :(得分:1)
您应该删除DAO实现上的@Transactional注释。而是在您的服务方法中;
@Override
@Transactional
public void addGrade(Grade grade) {
gradeDao.addGrade(grade);
}
对于所有数据库操作,只有服务实现需要@Transactional。
答案 3 :(得分:0)
正如Narmer所说,您将所有数据库配置放在servlet-context.xml
中,它应该进入root-context.xml
。但问题的真正原因(或其症状)是你没有使用事务代理,因为它可以在stacktrace中看到:GradeController.saveGrade
直接调用GradeServiceImpl.addGrade
,而GradeDaoImpl.addGrade
反过来直接调用@Transactional
}。
通常,您应该仅将@Autowired
private GradeService gradeService;
注释放在服务层中,而不应放在dao层中(只有一个事务层)。您应该验证是否从控制器自动装配服务
<tx:annotation-driven/>
请尝试仅使用一个事务层,并说出stacktrace是否显示事务代理使用情况。
编辑:
您的配置中还有另一个问题:当弹簧需要正确处理@Transactional
注释时,您没有{{1}}标记。
答案 4 :(得分:0)
以下是发生的事情:
当您使用sessionFactory.getCurrentSession()
而不是sessionFactory.openSession()
时,hibernate会查找绑定到应用程序上下文线程的会话实例(换句话说,单个会话实例将由hibernate管理并在getCurrentSession时返回会话工厂调用()。
现在要配置绑定到应用程序上下文线程的会话,您必须在hibernate属性中指定它。您可以通过将以下属性添加到hibernateProperties
来执行此操作:
<beans:prop key="hibernate.current_session_context_class">thread</beans:prop>
sessionFactory.openSession()
在没有hibernate属性的情况下工作正常的原因是hibernate不会查找绑定到应用程序上下文的session
,每次调用openSession()
时都需要创建一个新的会话实例sessionFactory
。
希望这会对你有所帮助。
答案 5 :(得分:-2)
尝试使用旧版本的spring ...我使用spring 3.2.8.RELEASE with hibernate 4.2.11.Final ...