Usually when defining a DAO, you would have a setter for the datasource on the DAO object. My problem is that our datasource varies dynamically based on the request to the server. i.e. every request can access different database instance.
The request holds logical properties, that later can be used to retrieve the connection to the DB of the request.
So when dependency injecting the DAO to the business logic object, I need a way to set the properties on the DAO at runtime (not configuration time).
One solution is to store the datasource on the thread local, but I don't really like messing with thread local variables.
Another option is to have an initialize method on the business logic object that calls initialize on the DAO with the request properties.
I guess it's a common problem, can you suggest a common solution?
Your problem is a little confusing. Having one DAO access multiple different datasources would seem to be a maintenance nightmare. As a result, you should define one DAO interface containing all the methods you would want to call. For each database you are connecting to I would construct a new class that implements your DAO interface. This allows you to have multiple implementations. I would then store these implementations (each that has its own datasource) in a Map (java.util.Map), using your "logical properties" as the key to the map. Since all your DAO Implementations implement your interface you will be able to cast them to the interface and use them interchangeably. On your business object, you would inject the Map of DAO implementations. I hope this helps your design.
I had such a problem on a client/server project. Client and Server projects was sharing Dao interfaces. And When I used to do database operation I had to select suitable Dao implementation. My solution was like this :
IVehicleDao vehicleDao =daoFactory.Get<IVehicleDao>(parameters);
vehicleDao.doSomething();
Get dao from Factory by passing parameters.Inside Dao factory decide which Dao implementation to return..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With