Java – How to design DAOs when the datasource varies dynamically

daojavaspring

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?

Best Solution

It sounds like your problem is that you are creating a single DAO instance for your application. You either need to create a separate instance for each datasource (maybe making some kind of dao controller to manage it all for you) or possibly allow your methods in your dao to be static and pass all information about how to connect to the datasource along with the data you are persisting into every method.