0

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.

sriharishk
  • 11
  • 3

1 Answers1

0

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

shankarsh15
  • 1,947
  • 1
  • 11
  • 16
  • Thanks for response, we don't want to introduce a specific implementation class as the implementation looks exactly same, the problem here is because of different schemas in which data is stored. All the application logic will remain same. So we are looking to find a way to dynamically specify transactionmanager based on the parameter received to the method. – sriharishk May 26 '16 at 16:57