Jayesh A Lalwani wrote:You can't have one EMF going to 2 PUs. One EMF will always manage 1 PU. You need to create 2 EMFs and inject the PU that you want to use into your DAO class.
I have a similar problem where I need to be able to connect to multiple databases from the same application. A thread will always connect to one database. All databases are identical. Each client has it's own schema, and at runtime, I need to connect to the correct database.
What I ended up doing is I extended HibernatePersistenceProvider. This extended provider contains a map of HibernatePersistenceProvider; one for each client. I have a thread local variable that contains the name of the client. This is set before any DAO calls are made. My Extended Persistence Provider checks the thread local variable and delegates all calls to the correct real HibernatePersistenceProvider. I used the same pattern with DataSource too. I extended DataSource to contain a map of other DataSource; one for each client. In both cases, if my extended class sees a new client, it creates a PersistenceProvider/DataSource for that client and puts it in the map (note thread safety important here )
So, I have only one PU that uses my extended persistence provider. I configured EMF to use this PU. I provide the extended datasource to the EMF. This EM is injected into my DAO classes. At run time, the service that recieves the request, sets the thread local variable and calls the DAO. DAO calls EM, EM calls the Persistence Provider. Persistence Provider routes all the calls to the "real" Persistence Provider. Internally the real persistence provider calls my extended data source, which uses the same thread local variable to route the calls to the real data source.