“找不到当前线程的会话”在改变会话的访问方法之后 [英] "No Session found for current thread" after changing access method to the session

查看:110
本文介绍了“找不到当前线程的会话”在改变会话的访问方法之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Spring MVC项目。我直接使用Hibernate。在我的项目中发生错误没有找到当前线程的会话。我知道在stackoverflow和网络上的其他地方,这个错误是非常普遍的。但我还没有找到解决我的问题的工作方案。



我对Hibernate Session Factory的正确配置有一个未解决的问题。我在这里描述了它:我可以使用在DispatcherServlet Context中声明的Hibernate Session Factory而不是hibernate.cfg.xml吗?但是最后我正在使用 hibernate.cfg.xml 文件以及在DispatcherServlet上下文文件中定义的Hibernate Session Factory。我做了一些简单的操作,例如在数据库中持久化类。一切都很好。



目前我的项目与 Spring MVC Hibernate 。我已经为我的类添加了一些注释,并且创建了一些新的服务类。



我的ServletDispatcher上下文文件包含以下定义:

 < annotation-driven /> 
< context:annotation-config />
< context:component-scan base-package =finances.webapp/>

<! - 数据源 - >
< beans:bean id =dataSourceclass =org.springframework.jdbc.datasource.DriverManagerDataSource>
< beans:property name =driverClassNamevalue =com.mysql.jdbc.Driver/>
< beans:property name =urlvalue =jdbc:mysql:// localhost / finances/>
< beans:property name =usernamevalue =root/>
< beans:property name =passwordvalue =root/>
< / beans:bean>
<! - 数据源结束 - >

<! - Hibernate会话工厂 - >
< beans:bean id =sessionFactoryclass =org.springframework.orm.hibernate4.LocalSessionFactoryBean>
< beans:property name =dataSource>
< beans:ref bean =dataSource/>
< / beans:property>
< beans:property name =configLocationvalue =classpath:hibernate.cfg.xml/>
< / beans:bean>
<! - Hibernate会话工厂结束 - >

< beans:bean id =transactionManagerclass =org.springframework.orm.hibernate4.HibernateTransactionManager>
< beans:property name =sessionFactoryref =sessionFactory/>
< / beans:bean>

< beans:bean id =transactionInterceptorclass =org.springframework.transaction.interceptor.TransactionInterceptor>
< beans:property name =transactionManagerref =transactionManager/>
< beans:property name =transactionAttributes>
< beans:道具>
< beans:prop key =save> PROPAGATION_REQUIRED< / beans:prop>
< / beans:道具>
< / beans:property>
< / beans:bean>

在我的pom.xml文件中,根据ORM我只有这两个依赖项:

 <! -  Hibernate  - > 
< dependency>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-entitymanager< / artifactId>
< version> 4.1.4.Final< / version>
< /依赖关系>

<! - EJB - >
< dependency>
< groupId> javax.ejb< / groupId>
< artifactId> ejb-api< / artifactId>
< version> 3.0< / version>
< scope>提供< / scope>
< /依赖关系>

也许问题在这里?但是我之前没有任何问题。



这是我的控制器的代码:

  UsersEntity user2 = new UsersEntity(qwerty,qwerty,true); 
usersService.addUser(user2);

问题没有找到当前线程的会话在调用 addUser()方法时发生。



我的DAO类:

  @Repository 
public class UsersHome {

@Autowired
private SessionFactory sessionFactory;

public void persist(UsersEntity transientInstance){
sessionFactory.getCurrentSession()。persist(transientInstance);
}
}

我的服务:

  @Service 
public class UsersService {

@Autowired
private UsersHome usersHome;

@Transactional(propagation = Propagation.REQUIRED)
public void addUser(UsersEntity user){
usersHome.persist(user);


$ / code>

当我更改方法体时,此代码已停止工作在 UsersHome 类中。以前,我在我的行动开始之前开始会议,在我的行动结束后开始会议。但使用注释和事务它应该工作?请给我一些建议。

编辑

 <冬眠-结构> 
< session-factory>
< property name =dialect> org.hibernate.dialect.MySQLDialect< / property>
< property name =show_sql> true< / property>
< property name =hbm2ddl.auto>更新< / property>
< property name =connection.url> jdbc:mysql:// localhost / finances< / property>
< property name =connection.driver_class> com.mysql.jdbc.Driver< / property>
< property name =connection.username> root< / property>
< property name =connection.password> root< / property>
< mapping class =finances.webapp.entities.AuthoritiesEntity/>
< mapping class =finances.webapp.entities.ExpensesEntity/>
< mapping class =finances.webapp.entities.ExpensesCategoriesEntity/>
< mapping class =finances.webapp.entities.ExpensesObjectsEntity/>
< mapping class =finances.webapp.entities.IncomesEntity/>
< mapping class =finances.webapp.entities.UsersEntity/>
< / session-factory>
< / hibernate-configuration>

编辑#2

  org.springframework.beans.factory.BeanCreationException:使用
名称'usersService'创建bean时出错:注入自动装配的依赖关系失败;嵌套异常
是org.springframework.beans.factory.BeanCreationException:无法自动装载
字段:private finances.webapp.dao.UsersHome
finances.webapp.services.UsersService.usersHome;
嵌套异常是org.springframework.beans.factory.BeanCreationException:
创建名为'usersHome'的bean时出错:注入自动装配依赖项
失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:
无法自动装入字段:private org.hibernate.SessionFactory
finances.webapp.dao.UsersHome.sessionFactory;嵌套的异常是
org.springframework.beans.factory.BeanCreationException:在ServletContext资源中定义的
名称'sessionFactory'创建bean时出错
[/ WEB-INF / spring / appServlet / servlet-context .xml]:调用init方法
失败;嵌套异常是java.lang.NoClassDefFoundError:
org / hibernate / cfg / EJB3DTDEntityResolver

编辑#3



我的 root-context.xml 文件:

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

<! - 根上下文:定义对所有其他Web组件可见的共享资源 - >

< / beans>

我的整个 spring-config.xml file:

 <?xml version =1.0encoding =UTF-8?> 
< beans:beans xmlns =http://www.springframework.org/schema/mvc
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xmlns:beans =http://www.springframework.org/schema/beans
xmlns:context =http://www.springframework.org/schema/context
xsi:schemaLocation =http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http:// www。 springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http:// www .springframework.org /模式/上下文/弹簧上下文3.0.xsd>

<! - DispatcherServlet上下文:定义这个servlet的请求处理基础结构 - >

<! - 启用Spring MVC @Controller编程模型 - >
< annotation-driven />
< context:annotation-config />
< context:component-scan base-package =finances.webapp/>

<! - 通过高效地提供$ {webappRoot} / resources目录中的静态资源来处理资源的HTTP GET请求 - >
< resource mapping =/ resources / **location =/ resources //>

<! - < beans:bean id =tilesConfigurerclass =org.springframework.web.servlet.view.tiles2.TilesConfigurer> - >
<! - < beans:property name =definitions> - >
<! - < beans:list> - >
<! - < beans:value> /WEB-INF/tiles-definitions.xml< / beans:value> - >
<! - < / beans:list> - >
<! - < / beans:property> - >
<! - < / beans:bean> - >

<! - < beans:bean id =viewResolverclass =org.springframework.web.servlet.view.UrlBasedViewResolver> - >
<! - < beans:property name =viewClassvalue =org.springframework.web.servlet.view.tiles2.TilesView/> - >
<! - < / beans:bean> - >

<! - 数据源 - >
< beans:bean id =dataSourceclass =org.springframework.jdbc.datasource.DriverManagerDataSource>
< beans:property name =driverClassNamevalue =com.mysql.jdbc.Driver/>
< beans:property name =urlvalue =jdbc:mysql:// localhost / finances/>
< beans:property name =usernamevalue =root/>
< beans:property name =passwordvalue =root/>
< / beans:bean>
<! - 数据源结束 - >

<! - Hibernate会话工厂 - >
< beans:bean id =sessionFactoryclass =org.springframework.orm.hibernate4.LocalSessionFactoryBean>
< beans:property name =dataSourceref =dataSource/>
< beans:property name =configLocationvalue =classpath:hibernate.cfg.xml/>
< / beans:bean>
<! - Hibernate会话工厂结束 - >

< beans:bean id =transactionManagerclass =org.springframework.orm.hibernate4.HibernateTransactionManager>
< beans:property name =sessionFactoryref =sessionFactory/>
< / beans:bean>

< beans:bean id =transactionInterceptorclass =org.springframework.transaction.interceptor.TransactionInterceptor>
< beans:property name =transactionManagerref =transactionManager/>
< beans:property name =transactionAttributes>
< beans:道具>
< beans:prop key =save> PROPAGATION_REQUIRED< / beans:prop>
< beans:prop key =persist> PROPAGATION_REQUIRED< / beans:prop>
< / beans:道具>
< / beans:property>
< / beans:bean>

< / beans:beans>


解决方案

尝试删除transactionInterceptor code> @Transaction 属性集,并且还有标签<注解驱动/> 。或者添加到 persist()方法的transactionInterceptor键

 < bean :prop key =persist> PROPAGATION_REQUIRED< / beans:prop> 

可能会有所帮助。

编辑:
我重新创建了你的配置并且它可以工作。

这是它的弹性配置:

 <?xml version =1.0encoding =UTF-8?> 
< beans xmlns =http://www.springframework.org/schema/beans
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xmlns:context =http://www.springframework.org/schema/context
xmlns:tx =http://www.springframework.org/schema/tx
xmlns :jdbc =http://www.springframework.org/schema/jdbc
xsi:schemaLocation =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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http:/ /www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
>

< context:annotation-config />
< context:component-scan base-package =finances.webapp/>


< jdbc:embedded-database id =dataSourcetype =H2/>

< bean id =sessionFactoryclass =org.springframework.orm.hibernate4.LocalSessionFactoryBean>
< property name =dataSourceref =dataSource/>
< property name =configLocationvalue =classpath:hibernate.cfg.xml/>
< / bean>

< tx:annotation-driven />

< bean id =transactionManagerclass =org.springframework.orm.hibernate4.HibernateTransactionManager>
< property name =sessionFactoryref =sessionFactory/>
< / bean>

< / beans>

这是hibernate的配置:

 <?xml version =1.0encoding =UTF-8?> 
<!DOCTYPE hibernate-configuration PUBLIC - // Hibernate / Hibernate配置DTD 3.0 // EN
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\"> ;
< hibernate-configuration>
< session-factory>
< property name =dialect> org.hibernate.dialect.H2Dialect< / property>
< property name =show_sql> true< / property>
< property name =hbm2ddl.auto>更新< / property>
< mapping class =finances.webapp.bean.UsersEntity/>
< / session-factory>
< / hibernate-configuration>

依赖于pom.xml

 <性状> 
< org.springframework.version> 3.1.0.RELEASE< /org.springframework.version>
< org.hibernate.version> 4.1.4.Final< /org.hibernate.version>
< / properties>
<依赖关系>
< dependency>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-entitymanager< / artifactId>
< version> $ {org.hibernate.version}< / version>
< /依赖关系>
< dependency>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-core< / artifactId>
< version> $ {org.hibernate.version}< / version>
< /依赖关系>

< dependency>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-annotations< / artifactId>
< version> 3.5.6-最终< / version>
< /依赖关系>

< dependency>
< groupId> javax.ejb< / groupId>
< artifactId> ejb-api< / artifactId>
< version> 3.0< / version>
< scope>提供< / scope>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-core< / artifactId>
< version> $ {org.springframework.version}< / version>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-context< / artifactId>
< version> $ {org.springframework.version}< / version>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-tx< / artifactId>
< version> $ {org.springframework.version}< / version>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-jdbc< / artifactId>
< version> $ {org.springframework.version}< / version>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-orm< / artifactId>
< version> $ {org.springframework.version}< / version>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-aop< / artifactId>
< version> $ {org.springframework.version}< / version>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-webmvc< / artifactId>
< version> $ {org.springframework.version}< / version>
< /依赖关系>
< dependency>
< groupId> cglib< / groupId>
< artifactId> cglib< / artifactId>
< version> 2.2.2< / version>
< /依赖关系>


<! - 仅供测试 - >
< dependency>
< groupId> com.h2database< / groupId>
< artifactId> h2< / artifactId>
< version> 1.3.168< / version>
< /依赖关系>

< dependency>
< groupId> org.testng< / groupId>
< artifactId> testng< / artifactId>
< version> 6.1.1< / version>
< scope> test< / scope>
< /依赖关系>

unit-test:

  public class TestPersist {
@ org.testng.annotations.Test $ b $ public void testPersistence()throws Exception {

ApplicationContext ctx = new ClassPathXmlApplicationContext(弹簧的context.xml);
Assert.assertNotNull(ctx);

UsersService userService = ctx.getBean(UsersService.class);

Assert.assertNotNull(userService);
UsersEntity user2 = new UsersEntity();
user2.setEnable(true);
user2.setLogin(querty);
user2.setName(user2);

userService.addUser(user2);


$ b code
$ b

和单元测试输出:
$ / p>

  2012年9月8日下午2:55:37 org.springframework.context.support.AbstractApplicationContext prepareRefresh 
INFO:Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5d3ad33d:启动日期[Sat Sep 08 14:55:37 MSK 2012];上下文层次结构的根
2012年9月8日下午2时55分37秒org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO:从类路径资源加载XML bean定义[spring-context.xml ]
2012年9月8日上午2:55:37 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO:预先实例化org.springframework.beans.factory.support.DefaultListableBeanFactory中的单例6cb32ed4:定义bean [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context .annotation.internalPersistenceAnnotationProcessor,usersHome,usersService,数据源,SessionFactory对象,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction .annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager的,org.springframework.context.annotation.ConfigurationClassPostProcessor $ ImportAwareBeanPostProcessor#0];工厂层次结构的根
2012年9月8日下午2时55分37秒org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory initDatabase
INFO:创建嵌入式数据库'dataSource'
2012年9月8日2:55:38 PM org.hibernate.annotations.common.Version< clinit>
INFO:HCANN000001:Hibernate Commons Annotations {4.0.1.Final}
2012年9月8日下午2:55:38 org.hibernate.Version logVersion
INFO:HHH000412:Hibernate Core {4.1 .4.Final}
2012年9月8日下午2:55:38 org.hibernate.cfg.Environment< clinit>
INFO:HHH000206:找不到hibernate.properties
2012年9月8日下午2:55:38 org.hibernate.cfg.Environment buildBytecodeProvider
INFO:HHH000021:字节码提供程序名称:javassist
2012年9月8日下午2:55:38 org.hibernate.cfg.Configuration configure
INFO:HHH000044:从URL进行配置:file:/home/gr/dev/target/classes/hibernate.cfg.xml
2012年9月8日下午2时55分38秒org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
警告:HHH000223:识别过时的hibernate命名空间http://hibernate.sourceforge.net/。改为使用命名空间http://www.hibernate.org/dtd/。参考Hibernate 3.6迁移指南!
2012年9月8日上午2:55:38 org.hibernate.cfg.Configuration doConfigure
INFO:HHH000041:已配置SessionFactory:null
2012年9月8日下午2:55:38 org。 hibernate.dialect.Dialect< init>
INFO:HHH000400:使用方言:org.hibernate.dialect.H2Dialect
2012年9月8日下午2点55分38秒org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423:禁用上下文LOB创建作为JDBC驱动程序报告JDBC版本[3]小于4
2012年9月8日下午2:55:38 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399:使用默认事务策略(直接JDBC事务)
2012年9月8日下午2时55分38秒org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory< init>
INFO:HHH000397:使用ASTQueryTranslatorFactory
2012年9月8日上午2:55:38 org.hibernate.tool.hbm2ddl.SchemaUpdate执行
INFO:HHH000228:运行hbm2ddl模式更新
2012年9月8日下午2:55:38 org.hibernate.tool.hbm2ddl.SchemaUpdate执行
INFO:HHH000102:提取数据库元数据
2012年9月8日下午2:55:38 org.hibernate.tool .hbm2ddl.SchemaUpdate执行
信息:HHH000396:更新架构
2012年9月8日下午2:55:38 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
信息:HHH000262:表未找到:UsersEntity
2012年9月8日下午2:55:38 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO:HHH000262:表未找到:UsersEntity
2012年9月8日上午2:55 :39 PM org.hibernate.tool.hbm2ddl.SchemaUpdate执行
INFO:HHH000232:架构更新完成
2012年9月8日下午2:55:39 org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO:使用DataSource [org.springframework.jdbc.datasource.Sim Hibernate SessionFactory的pleDriverDataSource @ 79ef3ccd用于HibernateTransactionManager
Hibernate:插入UsersEntity(id,enable,login,name)值(空,?,?,?)
RemoteTestNG结束:2868毫秒


I am working on Spring MVC project. I am using Hibernate directly. The error No Session found for current thread has occurred in my project. I know that on stackoverflow and on other places on the web this error is very common. But I haven't found working solution to my issue.

I have had unresolved problem with proper configuration of Hibernate Session Factory. I have described it here: Can I use Hibernate Session Factory declared in DispatcherServlet Context instead of hibernate.cfg.xml? But finally I am using hibernate.cfg.xml file and also Hibernate Session Factory defined in DispatcherServlet Context file. I have done some simple operations like persisting classes in database. And everything was OK.

At this moment my project has a lot of in common with Spring MVC Hibernate. I have added some annotations to my classes and I have created some new services classes.

My ServletDispatcher Context file contains this definitions:

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

<!-- Data source -->
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <beans:property name="url" value="jdbc:mysql://localhost/finances" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="root" />
</beans:bean>
<!-- Data source end -->

<!-- Hibernate session factory -->
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource">
          <beans:ref bean="dataSource" />
    </beans:property>
    <beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
</beans:bean>
<!-- Hibernate session factory end -->

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

<beans:bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
    <beans:property name="transactionManager" ref="transactionManager" />
    <beans:property name="transactionAttributes">
        <beans:props>
            <beans:prop key="save">PROPAGATION_REQUIRED</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

In my pom.xml file I have only these two dependencies according to ORM:

<!-- Hibernate -->
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.1.4.Final</version>
</dependency>

<!-- EJB -->
<dependency>
   <groupId>javax.ejb</groupId>
   <artifactId>ejb-api</artifactId>
   <version>3.0</version>
   <scope>provided</scope>
</dependency>

Maybe problem is here? But I haven't any problem with missing packages earlier.

This is code from my controller:

UsersEntity user2 = new UsersEntity("qwerty", "qwerty", true);
usersService.addUser(user2);

The problem No Session found for current thread has occured during invoking addUser() method.

My DAO class:

@Repository
public class UsersHome {

    @Autowired
    private SessionFactory sessionFactory;    

    public void persist(UsersEntity transientInstance) {
        sessionFactory.getCurrentSession().persist(transientInstance);
    }
}

My service:

@Service
public class UsersService {

    @Autowired
    private UsersHome usersHome;

    @Transactional(propagation = Propagation.REQUIRED)
    public void addUser(UsersEntity user) {
        usersHome.persist(user);
    }
}

This code has stopped working when I have change method body in UsersHome class. Previously I have been starting session before my action and ending session after my action. But using annotations and transactions it should work? Please give me some suggestions.

EDIT

<hibernate-configuration>
    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="connection.url">jdbc:mysql://localhost/finances</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <mapping class="finances.webapp.entities.AuthoritiesEntity"/>
        <mapping class="finances.webapp.entities.ExpensesEntity"/>
        <mapping class="finances.webapp.entities.ExpensesCategoriesEntity"/>
        <mapping class="finances.webapp.entities.ExpensesObjectsEntity"/>
        <mapping class="finances.webapp.entities.IncomesEntity"/>
        <mapping class="finances.webapp.entities.UsersEntity"/>
    </session-factory>
</hibernate-configuration>

EDIT #2

org.springframework.beans.factory.BeanCreationException: Error creating bean with 
name 'usersService': Injection of autowired dependencies failed; nested exception 
is org.springframework.beans.factory.BeanCreationException: Could not autowire 
field: private finances.webapp.dao.UsersHome 
finances.webapp.services.UsersService.usersHome;
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'usersHome': Injection of autowired dependencies 
failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private org.hibernate.SessionFactory
finances.webapp.dao.UsersHome.sessionFactory; nested exception is 
org.springframework.beans.factory.BeanCreationException: Error creating bean with
name 'sessionFactory' defined in ServletContext resource 
[/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method 
failed; nested exception is java.lang.NoClassDefFoundError: 
org/hibernate/cfg/EJB3DTDEntityResolver

EDIT #3

My root-context.xml file:

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

<!-- Root Context: defines shared resources visible to all other web components -->

</beans>

And my whole spring-config.xml file:

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

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<context:annotation-config />
<context:component-scan base-package="finances.webapp" />

<!-- Handles HTTP GET requests for resources by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!--<beans:bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">-->
    <!--<beans:property name="definitions">-->
        <!--<beans:list>-->
            <!--<beans:value>/WEB-INF/tiles-definitions.xml</beans:value>-->
        <!--</beans:list>-->
    <!--</beans:property>-->
<!--</beans:bean>-->

<!--<beans:bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">-->
    <!--<beans:property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />-->
<!--</beans:bean>-->

<!-- Data source -->
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <beans:property name="url" value="jdbc:mysql://localhost/finances" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="root" />
</beans:bean>
<!-- Data source end -->

<!-- Hibernate session factory -->
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource" />
    <beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
</beans:bean>
<!-- Hibernate session factory end -->

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

<beans:bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
    <beans:property name="transactionManager" ref="transactionManager" />
    <beans:property name="transactionAttributes">
        <beans:props>
            <beans:prop key="save">PROPAGATION_REQUIRED</beans:prop>
            <beans:prop key="persist">PROPAGATION_REQUIRED</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

</beans:beans>

解决方案

Try to remove "transactionInterceptor", you already have @Transaction attribute set and also have tag <annotation-driven/>. Or add to transactionInterceptor key for persist() method

<beans:prop key="persist">PROPAGATION_REQUIRED</beans:prop>

Maybe it help.

EDIT: I recreated your configuration and it works.

this it spring config:

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/jdbc
        http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        ">

    <context:annotation-config />
    <context:component-scan base-package="finances.webapp" />


    <jdbc:embedded-database id="dataSource" type="H2"/>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>

    <tx:annotation-driven />

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

</beans>

this is hibernate config:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="finances.webapp.bean.UsersEntity"/>
    </session-factory>
</hibernate-configuration>

dependency in pom.xml

<properties>
        <org.springframework.version>3.1.0.RELEASE</org.springframework.version>
        <org.hibernate.version>4.1.4.Final</org.hibernate.version>
    </properties>
  <dependencies>
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-entitymanager</artifactId>
          <version>${org.hibernate.version}</version>
      </dependency>
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <version>${org.hibernate.version}</version>
      </dependency>

      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-annotations</artifactId>
          <version>3.5.6-Final</version>
      </dependency>

      <dependency>
          <groupId>javax.ejb</groupId>
          <artifactId>ejb-api</artifactId>
          <version>3.0</version>
          <scope>provided</scope>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-orm</artifactId>
          <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
          <groupId>cglib</groupId>
          <artifactId>cglib</artifactId>
          <version>2.2.2</version>
      </dependency>


      <!--for test only -->
      <dependency>
          <groupId>com.h2database</groupId>
          <artifactId>h2</artifactId>
          <version>1.3.168</version>
      </dependency>

      <dependency>
          <groupId>org.testng</groupId>
          <artifactId>testng</artifactId>
          <version>6.1.1</version>
          <scope>test</scope>
      </dependency>

unit-test:

public class TestPersist {
    @org.testng.annotations.Test
    public void testPersistence() throws Exception {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml");
        Assert.assertNotNull(ctx);

        UsersService userService = ctx.getBean(UsersService.class);

        Assert.assertNotNull(userService);
        UsersEntity user2 = new UsersEntity();
        user2.setEnable(true);
        user2.setLogin("querty");
        user2.setName("user2");

        userService.addUser(user2);

    }
}

and unit-test output:

Sep 8, 2012 2:55:37 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5d3ad33d: startup date [Sat Sep 08 14:55:37 MSK 2012]; root of context hierarchy
Sep 8, 2012 2:55:37 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-context.xml]
Sep 8, 2012 2:55:37 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6cb32ed4: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,usersHome,usersService,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Sep 8, 2012 2:55:37 PM org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory initDatabase
INFO: Creating embedded database 'dataSource'
Sep 8, 2012 2:55:38 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Sep 8, 2012 2:55:38 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.4.Final}
Sep 8, 2012 2:55:38 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 8, 2012 2:55:38 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Sep 8, 2012 2:55:38 PM org.hibernate.cfg.Configuration configure
INFO: HHH000044: Configuring from URL: file:/home/gr/dev/target/classes/hibernate.cfg.xml
Sep 8, 2012 2:55:38 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Sep 8, 2012 2:55:38 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Sep 8, 2012 2:55:38 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Sep 8, 2012 2:55:38 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Sep 8, 2012 2:55:38 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Sep 8, 2012 2:55:38 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Sep 8, 2012 2:55:38 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Sep 8, 2012 2:55:38 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Sep 8, 2012 2:55:38 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Sep 8, 2012 2:55:38 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: UsersEntity
Sep 8, 2012 2:55:38 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: UsersEntity
Sep 8, 2012 2:55:39 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Sep 8, 2012 2:55:39 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.springframework.jdbc.datasource.SimpleDriverDataSource@79ef3ccd] of Hibernate SessionFactory for HibernateTransactionManager
Hibernate: insert into UsersEntity (id, enable, login, name) values (null, ?, ?, ?)
RemoteTestNG finishing: 2868 ms

这篇关于“找不到当前线程的会话”在改变会话的访问方法之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆