简体   繁体   中英

Spring dynamic transaction manager when there are multiple datasources

Requirement :

  1. I have transactional classes(With @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. (lets assume its kind of a tenant database) Is there a way to switch the transaction manager using AOP?

There are several steps to achieve that -

  1. Enable transaction management with @EnableTransactionManagement annotation at your @Configuration

  2. Define your 2 transaction manager( PlatformTransactionManager ) with some name (using @Qualifier annotation) for example - txMgr1 , txMgr2

  3. Use @Transactional("txMgr1) and @Transactional("txMgr2) annotation with your service class.

For detail please check these link below -

  1. Spring JPA – Multiple Databases
  2. Dynamic DataSource Routing with Spring @Transactional

I would prefer to work with multiple TransactionTemplates in this case. 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. In that case you would be able to get particular TransactionTemplate in you service from that map at runtime and use it. The result would be the same as using @Transactional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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