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

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

<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注解的地方。

所以解决方法就是分段扫描:

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>

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

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

更多解决方法看下面:

原文地址:https://www.cnblogs.com/myzoneliver/p/8358792.html