当前位置: 动力学知识库 > 问答 > 编程问答 >

Spring Txn - multiple datasources, transactionManaggers, How to decide on a transaction manager in runtime using @Transcational?

问题描述:

I am looking at a way to dynamically pick up a transaction manager instance at runtime.

I have a service which is dynamically selecting a DAO reference at runtime based on a parameter like below

@Mapper //Spring-MyBatis mapper

public interface DataMapper {

void save(Object domain);

}

public class DAO {

private DataMapper mapper;

public void save(Object domain) {

mapper.save(domain);

}

}

@Component

public class Service {

private DAO onlineBusinessDAO;

private DAO storeBusinessDAO;

public void save(String businessIdentifier, Object domain) {

identifyDAOBasedOn(businessIdentifier).save(domain);

}

private DAO identifyDAOBasedOn(String businessIdentifier) {

Switch(businessIdentifier) {

case "Online":

return onlineBusinessDAO;

case "Store":

return storeBusinessDAO;

}

}

}

In the above implementation based on businessIdentifier i am deciding on which instance of DAO to pickup and inside DAO i am using mybatis Mapper to do the job.

So i have multiple datasources (one for online, one for store) and multiple transactionManagers under a specific DAO instance.

i want to leverage spring @Transactional on save() under Service class but i need to specify which "transactionManager" reference to be used for @Transactional dynamically during runtime based on the businessIdentifier parameter.

Is there a way to achieve this?

I want to keep my code cleaner,lesser as much as possible - don't want to create 2 implementations of service or DAO using facade.

网友答案:

Please see steps below:

1.Create 2 different helper DAO implementation classes which use their own transactional managers.

2.Just make sure that both Implementation classes should implement a common interface

3.Main DAO class will keep both the helper implementations (make use of @Qualifier to distinguish those 2 helper implementations)

4.Main DAO will get a datasource name as a parameter and based on it will call method of proper helper bean

分享给朋友:
您可能感兴趣的文章:
随机阅读: