了解嵌套的Spring @Transactional如何工作

时间:2013-07-17 11:14:06

标签: spring jpa transactional

我正在将一个EJB应用程序移植到Spring,而我正面临一些问题。 应用程序使用eclipselink独立运行(这就是我们选择spring的原因)。

在这个应用程序中,我需要创建一个Order,我首先需要创建一个Customer,OrderLines,然后为此订单添加一个Payment。

问题在于我想在单个事务中进行所有插入,这样如果付款未能保留,则不能保留任何内容。我试图实现这一点,但看起来我正在跨越多个独立事务,因为如果发生故障,数据会持久保存到数据库(例如:付款失败,无论如何都会创建客户)。

以下是切入点:

public static void main(String[] args) {
    AbstractApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
    BeanFactory beanFactory = (BeanFactory) context;
    MyService service = beanFactory.getBean(MyService.class);
    service.getNewOrders(true);
}

这是我正在解决的bean(使用beanFactory.getBean):

@Component
@Scope("prototype")
public class MyService {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentService paymentService;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public void getNewOrders(boolean formattedOutput) {
        try {
            List<RawData> rawData = // Acquire data from a remote web service (http rest based)

            for (RawData data : rawData) {
                try {
                    this.handleOrder(data);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    private Order handleOrder(RawData rawData) throws Exception {
        Customer customer = new Customer();
        // Fill customer with rawData
        this.customerService.create(customer);

        Order order = new Order();
        order.setCustomer(customer);
        // Fill order with rawData
        this.orderService.create(order);

        Payment payment = new Payment();
        payment.setOrder(order);
        // Fill payment with rawData
        this.paymentService.create(payment);

        return order;
    }
}

每项服务如下所示:

@Service
@Transactional
public class CustomerService {

    @Autowired
    private CustomerDao customerDao;

    public void create(Customer customer) {
        // some works on customer fields (checking values etc)
        this.customerDao.create(customer);
    }
}

所有这些都由Dao支持:

@Repository
public class CustomerDao {

    @PersistenceContext
    protected EntityManager em;

    public void create(Customer customer) {
        this.em.persist(customer);
    }
}

以下是来自maven pom.xml的一些依赖项:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>com.jolbox</groupId>
        <artifactId>bonecp</artifactId>
        <version>0.8.0-rc1</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.25</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>javax.persistence</artifactId>
        <version>2.0.3</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.3.2</version>
    </dependency>

这是persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <shared-cache-mode>NONE</shared-cache-mode>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/db" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="" />
        </properties>
    </persistence-unit>
</persistence>

弹簧配置如下:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="myDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="jpaPropertyMap">
            <map>
                <entry key="eclipselink.weaving" value="false" />
            </map>
        </property>
    </bean>

    <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="myEmf" />
    </bean>

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

    <context:component-scan base-package="com.application" />

</beans>

修改

从main添加了ApplicationContext的创建,并从MyService.java

添加了一个省略的方法

1 个答案:

答案 0 :(得分:5)

如何调用服务方法,因为它是私有的?它应该是公开的。 Spring事务拦截器无法拦截私有方法,CGLib动态代理也无法覆盖它们。

编辑:好的,这是通常的问题。您从main方法调用方法getNewOrders(),它是公共的和事务性的。 Spring拦截器拦截此方法调用。由于没有事务并且该方法被标记为SUPPORTS,因此Spring不会启动任何事务。

然后此方法调用私有handleOrder()方法。请注意,不仅方法是私有的,这使得Spring无法拦截方法调用,但调用是从组件中的方法到同一组件中的方法。所以即使方法是公开的,Spring也无法拦截这种方法调用。事务处理是基于代理的:

method --> transactional proxy --> Spring bean 1 --> transactional proxy --> Spring bean2

在这种情况下,由于您没有调用另一个组件的方法,因此没有代理拦截,也没有启动任何事务。

method --> transactional proxy --> Spring bean 1 --> transactional proxy --> Spring bean2
                                      ^   |
                                      |___|

所以,你要做的是

  • 创建另一个Spring bean'OrderHandler,例如)
  • 将handleOrder()方法移动到此Spring bean,将其公开
  • 在MyService中注入OrderHandler

它会正常工作。

Spring documentation

详细说明了这一点