javax.persistence.TransactionRequiredException: Executing an update/delete query

这个问题出如今整合springmvc+spring4+hibernate5的时候出现的。首先事务要配好,我是这样配置的:html

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

<tx:annotation-driven transaction-manager="txManager"/>

//以后在合适的位置添加注解(通常在实现类或方法上):@Transactional
//添加事务也能够解决这个异常:Could not obtain transaction-synchronized Session for current thread

可是设置了以后事务好像没生效,在查看spring官方文档中说了这么一句:

就说若是你在springmvc中配置了<tx:annotation-driven/>,那么spring中的
<tx:annotation-driven transaction-manager="txManager"/>就失效了,他不会扫描除了controller之外的包中的有@Transactional注解的地方。java

因此解决方法就是分段扫描:spring

SpringMVC.xml配置文件--> 只扫描controller组件 注意使用 use-default-filters="false" 

<context:component-scan base-package="com.yx.*" use-default-filters="false" > 
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/> 
</context:component-scan> 


ApplicationContext.xml配置文件-->扫描除controller外的全部组件 

<context:component-scan base-package="com.yx.*" > 
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/> 
</context:component-scan>

上面方法是:这位仁兄 提供的。express

在此以前我看过其余解决方法,如:
@Transactional所导的包是:org.springframework.transaction.annotation.Transactionalsession

更多解决方法看下面:mvc

  • https://stackoverflow.com/questions/24046913/not-active-transaciotn-javax-persistence-transactionrequiredexception-executin
  • https://stackoverflow.com/questions/12317904/transactionrequiredexception-executing-an-update-delete-query
相关文章
相关标签/搜索