我是Spring的新手,我想知道是否可以在同一应用程序中使用多个事务管理器?
我有两个数据访问层-一个用于两个数据库。我想知道,你如何在一个层使用一个事务管理器,而在另一层使用另一个事务管理器。我不需要在两个数据库之间都执行事务。但是我确实需要分别在每个数据库上执行事务。我创建了一个图像来帮助概述我的问题:
这是我的应用程序上下文配置:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:component-scan base-package="cheetah.repositories" /> <tx:annotation-driven /> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="accounts" /> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> </beans>
这是使用此配置的示例:
@Repository public class JpaAccountRepository implements AccountRepository { @PersistenceContext(unitName = "cheetahAccounts") private EntityManager accountManager; @Override @Transactional public Account findById(long id) { Account account = accountManager.find(Account.class, id); return account; } }
因此,对于帐户存储库,我想使用将持久性单元设置为帐户的实体管理器工厂。但是,对于我的BusinessData存储库,我想使用具有不同持久性单元的实体管理器工厂。由于只能定义一个事务管理器bean,因此如何针对不同的存储库使用不同的事务管理器?
在使用@Transactional注释的地方,可以通过将属性集添加到Bean名称或限定符来指定要使用的事务管理器。例如,如果你的应用程序上下文使用限定符定义了多个事务管理器:
@Transactional
<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>
你可以使用限定符指定要使用的事务管理器:
public class TransactionalService { @Transactional("account") public void setSomethingInAccount() { ... } @Transactional("businessData") public void doSomethingInBusinessData() { ... } }