这里我有下面的方法在弹簧控制器
@Override
@Transactional
public Customer updateCustomer(Custom customer) throws Exception {
.....
depatmentService.updateDepartment(department);
..........
}
我有下面的方法在辅助类
@Override
@Transactional(readOnly = false)
public Department updateDepartment(Department department) throws Exception {
.....
}
我观察到的是,一旦线程从方法updateDepartment
中出来,该方法下的变化就会被提交。我不确定为什么?默认传播是Propagation.REQUIRED
,也就是Support a current transaction, create a new one if none exists.
那么为什么方法updateDepartment
的事务与方法updateCustomer
是分开的呢?
我正在使用JPA(hibernate实现)与spring事务。此外,我没有看到显式设置行为propagation
在xml
spring配置中事务管理的相关部分
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources" value="META-INF/custom-mappings.hbm.xml" />
<property name="packagesToScan" value="com..., ...Other packages" />
<property name="jpaVendorAdapter">
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
...........
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="org.hibernate.envers.default_schema">${jdbc.audit.schema}</prop>
.........
<prop key="hibernate.session_factory_name">SessionFactory</prop>
</props>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="javax.persistence.validation.factory">
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</entry>
</map>
</property>
</bean>
我有与控制器相关的配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
在控制器方法上使用@Transactional
注释是不常见的。常用的用法是将事务划分放在服务级别。
事务性控制器是可能的,但有一些警告。首先,Spring事务管理基于Spring AOP,默认情况下使用JDK代理。它在服务级别工作得很好,因为服务是作为接口注入到控制器中的。但是控制器不是作为接口注入的,所以它不能工作,你必须使用类目标代理和CGLib代理才能工作。据报道,让控制器实现带有JDK代理的接口在某些Spring版本上可以工作,而在其他Spring版本上则失败:参见另一篇文章
TL/DR:除非你真的不能把事务划分放在服务级而不是控制器级。