Spring - Is it possible to use multiple transaction managers in the same application?

后端 未结 2 1863
不知归路
不知归路 2020-11-28 03:52

I\'m new to Spring and I\'m wondering if its possible to use numerous transaction managers in the same application?

I have two data access layers - one for both of t

相关标签:
2条回答
  • 2020-11-28 04:20

    This Spring Jira entry discusses the issue a bit:

    https://jira.spring.io/browse/SPR-3955

    I think it could be one transaction manager per connection if you're not using two-phase commit. You just need to create two transaction managers and inject them with the appropriate connection.

    But I must ask the question: why do you think you need two transaction managers? You can have more than one database connection. The DAOs that use the connections can and should be instantiated by different services, each of which can be annotated with their own transactional settings. One manager can accommodate both. Why do you think you need two?

    0 讨论(0)
  • 2020-11-28 04:44

    Where you use a @Transactional annotation, you can specify the transaction manager to use by adding an attribute set to a bean name or qualifier. For example, if your application context defines multiple transaction managers with qualifiers:

    <bean id="transactionManager1"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory1" />
        <qualifier value="account"/>
    </bean>
    
    <bean id="transactionManager2"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory2" />
        <qualifier value="businessData"/>
    </bean>
    

    You can use the qualifier to specify the transaction manager to use:

    public class TransactionalService {
    
        @Transactional("account")
        public void setSomethingInAccount() { ... }
    
        @Transactional("businessData")
        public void doSomethingInBusinessData() { ... }
    }
    
    0 讨论(0)
提交回复
热议问题