I think the best course of action would be creating a SessionFactory
for each data source, with possibly pooled connections - that's what's eqbridges suggested in his answer.
Now, Hibernate does have a ConnectionProvider
hook, so I suppose you could write an implementation that would return Connection
s to different data sources, depending on current thread of execution and some additional parameters. Theoretically, you can then have one SessionFactory
instance, which will be using different connections to different databases, supplied by your custom ConnectionProvider
implementation. But, one SessionFactory
holds quite a bit of data, and that data is then used by Hibernate internally, when opening a Session
for a unit of work. Plus, there's a second-level cache associated with it as well.
Unfortunately, how will the factory and Session
s you open from it behave in the face of such a provider is anybody's guess. It feels like a hack to me, and I doubt it was ever considered a viable use-case for a SessionFactory
. It can possibly lead to all kinds of, possibly very subtle, bugs or data corruption.
On another note, be sure to exactly measure the cost of creating multiple SessionFactories
- it may not be as high as you think. Be sure to compare that with the cost of simply opening the needed JDBC connections. I don't know what kind of results you might get, but I think you should be sure about performance before you resort to more hackish solutions.