Session绑定到线程

Session绑定到线程

本文介绍了我正在接收HibernateException“No Hibernate Session绑定到线程,并且配置不允许在此创建非事务性的一个”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 尽管这里有很多类似的问题,但对我而言似乎没有什么用处。当我调用sessionFactory.getCurrentSession()。createQuery(from Strings)。list(); 这里是我的root-context.xml: < beans xmlns =http://www.springframework.org/schema/beansxmlns:xsi =http: http://www.springframework.org/schema/aopxmlns:context =http://www.springframework.org/schema/上下文xmlns:jee =http://www.springframework.org/schema/jeexmlns:lang =http://www.springframework.org/schema/langxmlns:p =http:// www .springframework.org / schema / pxmlns:tx =http://www.springframework.org/schema/txxmlns:util =http://www.springframework.org/schema/utilxsi:schemaLocation =http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http:/ /www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring- context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http: //www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http ://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd\"> < context:annotation-config /> < context:component-scan base-package =org.vadim.testmvc.dao/> < context:component-scan base-package =org.vadim.testmvc.service/> < import resource =data.xml/> < / beans> 我的data.xml: < beans xmlns =http://www.springframework.org/schema/beansxmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns :aop =http://www.springframework.org/schema/aopxmlns:context =http://www.springframework.org/schema/contextxmlns:jee =http://www.springframework。 org / schema / jeexmlns:lang =http://www.springframework.org/schema/langxmlns:p =http://www.springframework.org/schema/pxmlns:tx =http ://www.springframework.org/schema/txxmlns:util =http://www.springframework.org/schema/utilxsi:schemaLocation =http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop。 xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http:// www.springframework.org/schema/lang/spring-lang.xsd h ttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http:// www .springframework.org /模式/ util的/弹簧util.xsd> < tx:注解驱动的事务管理器=transactionManager/> < bean id =transactionManagerclass =org.springframework.orm.hibernate3.HibernateTransactionManager> < property name =sessionFactoryref =sessionFactory/> < / bean> < bean id =messageSourceclass =org.springframework.context.support.ReloadableResourceBundleMessageSource> < property name =basenamevalue =classpath:messages/> < property name =defaultEncodingvalue =UTF-8/> < / bean> < bean id =propertyConfigurerclass =org.springframework.beans.factory.config.PropertyPlaceholderConfigurerp:location =/ WEB-INF / jdbc.properties/> < bean id =dataSourceclass =org.springframework.jdbc.datasource.DriverManagerDataSourcep:driverClassName =$ {jdbc.driverClassName}p:url =$ {jdbc。 databaseurl}p:username =$ {jdbc.username}p:password =$ {jdbc.password}/> < bean id =sessionFactoryclass =org.springframework.orm.hibernate3.LocalSessionFactoryBean> < property name =dataSourceref =dataSource/> < property name =configLocation> < value> classpath:hibernate.cfg.xml< / value> < / property> < property name =configurationClass> < value> org.hibernate.cfg.AnnotationConfiguration< / value> < / property> < property name =hibernateProperties> <道具> < prop key =hibernate.show_sql> true< / prop> < prop key =hibernate.dialect> $ {jdbc.dialect}< / prop> < prop key =hibernate.connection.charSet> UTF-8< / prop> < /道具> < / property> < / bean> < / beans> TestController.java(我删除了导入语句,不会重载问题): package org.vadim.testmvc; @Controller public class TestController { $ b $ @Autowired TestService testservice; 列表< String> list = new LinkedList< String>(); int i = 0; @RequestMapping(/) public String hello(){ returnredirect:/ helloworld; $ b @RequestMapping(value =/ helloworld)字符串listWord(Map< String,Object> map){ map.put(addRepeat ,新的Strings()); map.put(listStrings,testservice.listStrings()); 返回helloworld; $ b @RequestMapping(value =/ repeat,method = RequestMethod.POST) String addRepeat(@ModelAttribute(addRepeat)字符串,BindingResult结果){ testservice.addStrings(strings); 返回重定向:/ helloworld; TestService.java: package org.vadim.testmvc.service; @Service public class TestService { @Autowired TestDAO testdao; @Transactional public List< Strings> listStrings(){ return testdao.listStrings(); } @Transactional public void addStrings(String string){ testdao.addStrings(strings); } } 最后TestDAO.java: package org.vadim.testmvc.dao; @Transactional @Repository public class TestDAO { @Autowired private SessionFactory sessionFactory; public void addStrings(String string){ sessionFactory.getCurrentSession()。save(strings); } @SuppressWarnings(unchecked) public List< Strings> listStrings(){ return sessionFactory.getCurrentSession()。createQuery(from Strings)。list(); 发生异常后的堆栈: SEVERE:servlet [appServlet]与path [/ TestMVC]上下文中的Servlet.service()引发异常[Request processing failed;嵌套异常是org.hibernate.HibernateException:没有Hibernate Session绑定到线程,并且配置不允许在这里创建非事务性的一个],其根源为 org.hibernate.HibernateException:没有Hibernate Session绑定到线程,并且配置不允许在这里创建非事务性的在org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)在org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl .java:544) at org.vadim.testmvc.dao.TestDAO.listStrings(TestDAO.java:23) at org.vadim.testmvc.service.TestService.listStrings(TestService.java:18 ) at org.vadim.testmvc.TestController.listWord(TestController.java:30) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.j ava:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java: at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle( AnnotationMethodHandlerAdapter.java:414) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java: at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org .apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina .authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve .invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:851) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve .java:118) at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84) at org.apache.catalin a.connector.CoyoteAdapter.service(CoyoteAdapter.java:405) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:278) at org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:515)$ or $ $ b $ org.apache.tomcat.util.net.JIoEndpoint $ SocketProcessor.run(JIoEndpoint.java:300)在java.util.concurrent.ThreadPoolExecutor。 (ThreadPoolExecutor.java:1110)在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:603)在java.lang.Thread.run(Thread.java:722) hibernate.cfg.xml: <?xml version ='1.0'encoding ='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC - // Hibernate / Hibernate配置DTD // ENhttp://hibernate.sourceforge.net/hibernate-configuration-3.0。 DTD> < hibernate-configuration> < session-factory> < mapping class =org.vadim.testmvc.model.Strings/> < / session-factory> < / hibernate-configuration> Strings.java: package org.vadim.testmvc.model; @Entity @Table(name =STRINGS)公共类字符串{ @Id @Column(name =ID) @GeneratedValue 私人整数ID; public Integer getId(){ return id; } @Column(name =TEXT) private String text; public String getText(){ return text; } public void setText(String text){ this.text = text; } } 在这个问题上的每一个帮助。 解决方案我认为这个问题来自于你没有通过接口访问你的服务。默认情况下,Spring使用基于Java接口的代理。 顺便说一句,堆栈跟踪不包含任何事务性拦截器调用。 请参阅 Spring的这一段文档: $ b 元素上的proxy-target-class属性控制着什么类型的事务代理是为类创建的,这些类是用@Transactional注释注释的。如果 proxy-target-class属性设置为true,则基于类的代理将创建。如果proxy-target-class为false,或者如果省略了属性,则会创建标准的基于JDK接口的代理。 (见第7.6节代理机制讨论了不同的代理类型。) 因此,要么为您的事务服务和DAO引入接口,要么使用 proxy-target-class =true。 Despite the bunch of similar questions here nothing seems to be usefull to me. I get the exception when I call sessionFactory.getCurrentSession().createQuery("from Strings").list();Here is my root-context.xml:<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"><context:annotation-config/><context:component-scan base-package="org.vadim.testmvc.dao"/><context:component-scan base-package="org.vadim.testmvc.service"/><import resource="data.xml"/></beans>My data.xml:<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"><tx:annotation-driven transaction-manager="transactionManager"/><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"/></bean><bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"><property name="basename" value="classpath:messages"/><property name="defaultEncoding" value="UTF-8"/></bean><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties"/><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}"/><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property><property name="configurationClass"><value>org.hibernate.cfg.AnnotationConfiguration</value></property><property name="hibernateProperties"><props><prop key="hibernate.show_sql">true</prop><prop key="hibernate.dialect">${jdbc.dialect}</prop><prop key="hibernate.connection.charSet">UTF-8</prop></props></property></bean></beans>TestController.java (I removed the import statements not to overload the question):package org.vadim.testmvc;@Controllerpublic class TestController {@Autowired TestService testservice;List<String> list = new LinkedList<String>();int i=0;@RequestMapping("/")public String hello() { return "redirect:/helloworld";}@RequestMapping(value = "/helloworld")String listWord(Map<String, Object> map){ map.put("addRepeat", new Strings()); map.put("listStrings", testservice.listStrings()); return "helloworld";}@RequestMapping(value="/repeat", method = RequestMethod.POST)String addRepeat(@ModelAttribute("addRepeat") Strings strings, BindingResult result) { testservice.addStrings(strings); return "redirect:/helloworld";}}TestService.java:package org.vadim.testmvc.service;@Servicepublic class TestService {@AutowiredTestDAO testdao;@Transactionalpublic List<Strings> listStrings(){ return testdao.listStrings();}@Transactionalpublic void addStrings(Strings strings){ testdao.addStrings(strings);}}And finally TestDAO.java:package org.vadim.testmvc.dao;@Transactional@Repositorypublic class TestDAO{@Autowiredprivate SessionFactory sessionFactory;public void addStrings(Strings strings){ sessionFactory.getCurrentSession().save(strings);}@SuppressWarnings("unchecked")public List<Strings> listStrings(){ return sessionFactory.getCurrentSession().createQuery("from Strings").list();}}The stack after the exception occurs:SEVERE: Servlet.service() for servlet [appServlet] in context with path [/TestMVC] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here] with root causeorg.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one hereat org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:544)at org.vadim.testmvc.dao.TestDAO.listStrings(TestDAO.java:23)at org.vadim.testmvc.service.TestService.listStrings(TestService.java:18)at org.vadim.testmvc.TestController.listWord(TestController.java:30)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:601)at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:851)at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:278)at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)at java.lang.Thread.run(Thread.java:722)hibernate.cfg.xml:<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><mapping class="org.vadim.testmvc.model.Strings"/></session-factory></hibernate-configuration>Strings.java:package org.vadim.testmvc.model;@Entity@Table(name="STRINGS")public class Strings { @Id @Column(name="ID") @GeneratedValue private Integer id; public Integer getId(){ return id; } @Column(name="TEXT") private String text; public String getText(){ return text; } public void setText(String text){ this.text=text; }}I would appreciate every help in this issue. 解决方案 I think the problem comes from the fact that you're not accessing your service through an interface. By default, Spring uses Java interface-based proxies. BTW, the stack trace doesn't contain any transactional interceptor call.See the second note under this paragraph of the Spring documentation: The proxy-target-class attribute on the element controls what type of transactional proxies are created for classes annotated with the @Transactional annotation. If proxy-target-class attribute is set to true, class-based proxies are created. If proxy-target-class is false or if the attribute is omitted, standard JDK interface-based proxies are created. (See Section 7.6, "Proxying mechanisms" for a discussion of the different proxy types.)So, either introduce interfaces for your transactional services and DAOs, or use proxy-target-class="true". 这篇关于我正在接收HibernateException“No Hibernate Session绑定到线程,并且配置不允许在此创建非事务性的一个”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-29 10:58