简体   繁体   English

有多个数据源时的Spring动态事务管理器

[英]Spring dynamic transaction manager when there are multiple datasources

Requirement :要求 :

  1. I have transactional classes(With @Transaction)我有事务类(使用@Transaction)
  2. During the run time it will connect with only one data source在运行时它只会连接一个数据源
  3. But that data source can be changed one call to another depending on the required database.但是该数据源可以根据所需的数据库从一个调用更改为另一个调用。
public class EmployeeManagerImpls {

    @Autowired
    private employeeDao:

    @Transactional
    public void saveEmployee(Employee e) {
        employeeDao.saveEmployee(e);
    }
}

Employee Dao is has the cabality to select the required db based on the parameters. Employee Dao 具有根据参数选择所需数据库的能力。 (lets assume its kind of a tenant database) Is there a way to switch the transaction manager using AOP? (假设它是一种租户数据库)有没有办法使用 AOP 切换事务管理器?

There are several steps to achieve that -有几个步骤可以实现-

  1. Enable transaction management with @EnableTransactionManagement annotation at your @Configuration使用@Configuration @EnableTransactionManagement批注启用事务管理

  2. Define your 2 transaction manager( PlatformTransactionManager ) with some name (using @Qualifier annotation) for example - txMgr1 , txMgr2使用一些名称(使用@Qualifier注释)定义您的 2 个事务管理器( PlatformTransactionManager ),例如 - txMgr1 , txMgr2

  3. Use @Transactional("txMgr1) and @Transactional("txMgr2) annotation with your service class.对您的服务类使用@Transactional("txMgr1)@Transactional("txMgr2)注释。

For detail please check these link below -有关详细信息,请查看以下链接 -

  1. Spring JPA – Multiple Databases Spring JPA – 多个数据库
  2. Dynamic DataSource Routing with Spring @Transactional 使用 Spring @Transactional 进行动态数据源路由

I would prefer to work with multiple TransactionTemplates in this case.在这种情况下,我更愿意使用多个 TransactionTemplates。 You can create several instances of them for each DB at startup, then put them into map as values, and keys of that map would correspond the possible "flag values" of your DTO.您可以在启动时为每个数据库创建它们的多个实例,然后将它们作为值放入映射中,该映射的键将对应于您的 DTO 可能的“标志值”。 In that case you would be able to get particular TransactionTemplate in you service from that map at runtime and use it.在这种情况下,您将能够在运行时从该地图获取服务中的特定 TransactionTemplate 并使用它。 The result would be the same as using @Transactional.结果将与使用@Transactional 相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM