Pawan Patil
Pawan Patil

Reputation: 1157

Multiple Transaction managers in Spring JPA

I want to use two transaction managers as follows

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

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

and in my code there are tx:annotation-driven tags are present such as follows

 <tx:annotation-driven  mode="aspectj" transaction-manager="transactionManagerReadWrite"/>

  <tx:annotation-driven mode="aspectj" transaction-manager="transactionManagerReadOnly"/> 

but I read somewhere that there should be only one tx:annotation-driven present and refer another transaction manager by specifying in @Transaction tag such as folows

@Transactional("transactionManagerReadWrite")
@Transactional("transactionManagerReadOnly")

Following are my questions and queries

  1. Which transaction manager is considered as a valid candidate for @Transactional if there are two transaction managers present and two tx:annotation-driven tags present in configuration file if we don't specify the name of transaction manager explicitly in @Transactional annotation ?
  2. What would be the mode of second transaction manager if it is recommended to have only one tx:annotation-driven tag in application and we specify the mode in tx:annotation-driven tag only ? i.e. springs default mode is proxy mode and I want to use two transaction manager's with aspectj mode
  3. How to specify aspectj mode for second transaction manager if we can use only one tx:annotation-driven tag and default mode is proxy mode in spring ?

Upvotes: 1

Views: 2541

Answers (1)

M. Deinum
M. Deinum

Reputation: 125292

You can only have a single <tx:annotation-driven /> as that configured how @Transactional annotations are handled. You specify the mode (proxy or aspectj) and the default transaction manager to associate with @Transactional annotations.

The aspect is thus either applied through proxies (mode proxy) or load or compile time weaving (mode aspectj). There is just 1 aspect and that aspect either uses the default transaction manager or the one defined in the @Transactional annotation.

Given you specify the aspectj mode and transactionManagerReadWrite as the default transaction manager

<tx:annotation-driven  mode="aspectj" transaction-manager="transactionManagerReadWrite"/>

Now when using a plain @Transactional it will use transactionManagerReadWrite, when using @Transactional("transactionManagerReadOnly") it will use the transactionManagerReadOnly. Either one will be weaved in as aspectj is used as the mode to apply transactions.

Upvotes: 1

Related Questions