为什么此处的交易被视为两个单独的交易?

时间:2015-08-03 10:17:40

标签: java spring jpa

这里我在弹簧控制器中有以下方法

@Override
@Transactional
public Customer updateCustomer(Custom customer) throws Exception {
.....
depatmentService.updateDepartment(department);
..........


}

我在helper类中有以下方法

@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

分开

我在Spring事务中使用JPA(hibernate实现)。另外,我没有看到在xml中明确设置行为propagation

来自弹簧配置的事务管理的相关部分

<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">

1 个答案:

答案 0 :(得分:1)

对控制器方法进行@Transactional注释并不常见。通常用它来将事务划分放在服务级别。

交易控制器是可能的,但有一些警告。首先,Spring事务管理基于Spring AOP,默认使用JDK代理。它在服务级别工作正常,因为服务作为控制器中的接口注入。但是控制器不是作为接口注入的,所以它不起作用,你必须使用CGLib代理的类目标代理才能工作。据报道,控制器实现与JDK代理的接口可以在某些Spring版本上运行,而在其他版本上运行失败:请参阅this other post

TL / DR:除非你真的不能将事务划分放在服务级别而不是控制器级别。

相关问题