Spring上的嵌套事务

gab*_*uzo 15 spring annotations transactions

我在使用嵌套的Spring事务时发现了一些奇怪的行为:当在同一个类中,一个注释为@Transactional调用的方法时,另一个注释为@Transactional第二个注释的方法也没有被使用.

我们考虑以下课程:

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        final Main main = context.getBean(Main.class);
        // First Op
        System.out.println("Single insert: " + main.singleInsert());
        // Second Op
        main.batchInsert();
        // Third Op
        main.noTransBatchInsert();
    }

    @PersistenceContext
    private EntityManager pm;

    @Transactional(propagation=Propagation.REQUIRED)
    public void batchInsert() {
        System.out.println("batchInsert");
        System.out.println("First insert: " + singleInsert());
        System.out.println("Second insert: " + singleInsert());
    }

    public void noTransBatchInsert() {
        System.out.println("noTransBatchInsert");
        System.out.println("First insert: " + singleInsert());
        System.out.println("Second insert: " + singleInsert());
    }

    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public int singleInsert() {
        System.out.println("singleInsert");
        Pojo p = new Pojo();
        pm.persist(p);
        return p.getId();
    }
}
Run Code Online (Sandbox Code Playgroud)

该实体如果以下类:

@Entity
public class Pojo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Override
    public String toString() {
        return "Pojo: " + id;
    }

    public int getId() {
        return id;
    }
}
Run Code Online (Sandbox Code Playgroud)

和String部分applicationContext.xml:

<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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <tx:annotation-driven />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="MyPersistenceUnit" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

和配置类(我可以在applicationContext.xml中合并它).

@Configuration
@ImportResource("/META-INF/applicationContext.xml")
public class Config {

    @Bean
    public Main main() {
        return new Main();
    }
}
Run Code Online (Sandbox Code Playgroud)

为了完整性,persistence.xml文件:

<persistence 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" version="2.0">

    <persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>
            <property name="hibernate.hbm2ddl.auto" value="create" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
            <property name="hibernate.connection.driver_class" value="org.h2.Driver" />
            <property name="hibernate.connection.url" value="jdbc:h2:mem:TestDSJPA2;DB_CLOSE_DELAY=-1;LOCK_MODE=0" />
            <!--<property name="hibernate.connection.url" value="jdbc:h2:mem:TestDSJPA2;DB_CLOSE_DELAY=-1;LOCK_MODE=0" />-->
            <property name="hibernate.connection.username" value="sa" />
            <property name="hibernate.connection.password" value="" />
            <property name="hibernate.connection.autocommit" value="false"/>

            <property name="hibernate.c3p0.min_size" value="5" />
            <property name="hibernate.c3p0.max_size" value="20" />
            <property name="hibernate.c3p0.timeout" value="300" />
            <property name="hibernate.c3p0.max_statements" value="50" />
            <property name="hibernate.c3p0.idle_test_period" value="3000" />
        </properties>

    </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

因此,在主类中,第一个操作按预期在新事务中执行.输出(包括一些DEBUG消息)是:

DEBUG o.h.transaction.JDBCTransaction  - begin
singleInsert
DEBUG o.h.transaction.JDBCTransaction  - commit
Single insert: 1
Run Code Online (Sandbox Code Playgroud)

第二个操作给出以下输出:

batchInsert
singleInsert
DEBUG o.h.transaction.JDBCTransaction  - begin
First insert: 2
singleInsert
Second insert: 3
DEBUG
Run Code Online (Sandbox Code Playgroud)

这不是我所期望的,因为在注释singleInsert时@Transactional(propagation=Propagation.REQUIRES_NEW)我会期望为每次调用创建一个新的事务,这不是发生的事情,因为同一个顶级事务用于插入.

第三个操作失败,并且根本没有创建任何事务:

noTransBatchInsert
singleInsert
DEBUG o.h.e.def.AbstractSaveEventListener  - delaying identity-insert due to no transaction in progress
First insert: 0
singleInsert
DEBUG o.h.e.def.AbstractSaveEventListener  - delaying identity-insert due to no transaction in progress
Second insert: 0
Run Code Online (Sandbox Code Playgroud)

@Configurationbean中,Spring确保对同一类上的方法的调用是代理的,这显然不会发生在这里.有没有办法改变这种行为?

gab*_*uzo 9

当使用proxyAOP模式时,此行为是Spring记录的行为.可以通过切换到aspectj在编译或运行时执行代码检测的模式来更改它.


bre*_*dev 7

这不是@Transactional的具体问题.这是由于您的配置<tx:annotation-driven/>.

Spring使用两种不同的AOP机制:JDK动态代理或CGLIB.JDK动态代理是默认设置,它通过在运行时使用接口来工作.CGLIB通过在编译时生成子类来工作.如果你指定<tx:annotation-driven proxy-target-class="true"/>,Spring将使用CGLIB,你的第二个@Transactional将会触发.

你可以阅读更多关于主题在这里.