In one of my projects, I have an application that manages several clients (or customer if you prefer). For each of them, I have a dedicated schema on a database. However, th
If only one at a time will every be required, it makes it much simpler. Simply create a SessionFactory
per database. Avoid the HibernateUtils
static SessionFactory
instance approach and you won't have any problems.
A neat way to do this with Spring if you don't have too many databases (hundreds) is to instantiate a separate Spring ApplicationContext
for each one that contains the SessionFactoryBean
and DataSource
configurations specially for that database.
You can use Spring mechanisms like PropertyOverrideConfigurer
and a common parent ApplicationContext
to factor out all the common stuff so that your many child ApplicationContext
s are small and maintainable.
Then when a request comes in, just select the ApplicationContext
you want to work with and start pulling beans out of it.
If you want to do it without Spring, you could also create multiple SessionFactory
instances and store the "current" one in a static ThreadLocal
.
Unfortunately, the Real World often does require multiple databases/schemas, especially when you have a vendor product whose database must be distinct from your corporate databases.
Making an arbitrary number of databases would be a mess, and for that, you really SHOULD consider a better form of data organization. But for a fixed (hopefully small) set of databases, just define them in the persistence configuration with a separate PersistenceUnit for each (which implies a separate EntityManager).
Using your illustrated inheritance scheme, you would assign the appropriate EntityManager to each derived class, assuming that the framework lets you.