Skip to main content

Need to handle multiple databases; How to design with Spring?

2 replies [Last post]
Joined: 2007-03-21
Points: 0

I have a J2EE Web application with Servlets and Java ServerPages. Beside this I have a in-house developed API for certain services built using Hibernate and Spring with POJO's and some EJB.

There are 8 databases which will be used by the web application. I have heard that multiple datasources with Spring is hard to design around. Considering that I have no choice not to use Spring or Hibernate as the API's are using it.

Anyone have a good design spesification for how to handle multiple datasources. The datasource(database) will be chosen by the user in the web application.

I need to have the hibernateSessionFactory bean use the datasource which will be chosen by the user. I could certainly create several datasource beans in the Application Context xml file, but the problem is how do I get the chosen one to hibernateSessionFactoru

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-03-04
Points: 0

If you're forced to use Spring for your database config, you could try doing something like this:

Have 1 object that serves as a holder of the 8 different datasources.

Use Spring to configure that with the standard xml/setter mechanism as per normal.

Instead of having one thing datasource against this holder, try all 8.

Then, in this object what you do is you have a Map which is intiailly empty. As the setters are called by Spring instead of 'setting' a variable as you would normally in a setter, instead add the datasources to the Map.

So the code for the client's interaction with the back end, when it wants its datasource, it has stored the same name that you have stored that datasource with in the Map. And it has also been injected with this datasource holder.

Now, for the getter, simply hand it the parameter that identifies which of the datasources you wish to extract, and instead of simply returning the variable (as you would in a normal getter) you return the datasource you want out of the Map.

So everywhere you would have injected a datasource directly, you instead give inject the holder.

Each client must keep track of which datasource they are currently using, and that information must be available to the parts of the application which will use the datasources.

Disclaimer: Spring's config is probably sufficiently complex to be able to hand a list to the component in the initial setup (which may be better than what I describe), but I am not (by a long shot) a Spring expert.

Hope that helps.

Joined: 2004-06-18
Points: 0

if you have 8 databases, you will need 8 Hibernate SessionFactorys. Ain't got nothin' to do with Spring, though...