0

Here is a challenge that I found at my job: We have a java web application and several databases (one per customer) (The same database/metadata for each customer). Also there is a central database which keeps customers info such Database URL and forth.

At the login screen the user informs Customer ID, Login and Password, hit the login button then first the web application goes to the central database in order to find the Customer database's URL (I have a separate entity manager factory for it), then it goes back and create a new entity manager factory for that customer database. So far so good, I can see customer 1's data.

However when I logout and try to login under a different customer ID (which means a different database) the entity manager factory, which was created before, is still "connected" to the prior customer's database even having the application passing the parameters map containing the new database url.

My question is if there is a way to make JPA to connect to different databases without having to create an entity manager factory for each customer. I know that EntityManagerFactory objects caches all the database metadata so is there a way to change, say, the database url property and refresh the factory?

Thank you,

Gyo

3 Answers3

3

My question is if there is a way to make JPA to connect to different databases without having to create an entity manager factory for each customer.

I don't think so.

See Nayans answer here: When should EntityManagerFactory instance be created/opened? for more insight.

Community
  • 1
  • 1
hoipolloi
  • 7,678
  • 2
  • 24
  • 28
  • 1
    Actually, after digging on Google I found that from Hibernate 4.x it was introduced the Multi tenancy support [link](https://docs.jboss.org/hibernate/core/4.2/devguide/en-US/html/ch16.html) and that's what I need. – Gyowanny Pessatto Queiroz Feb 04 '14 at 22:43
  • @gyo I didn't know about that. You should create & accept an answer so others can learn. – hoipolloi Feb 05 '14 at 00:41
1

Actually, after digging on Google I found that from Hibernate 4.x it was introduced the Multi tenancy support and that's what I need. The next challenge is to do it from pure JPA instead of using Hibernate directly and think it's going to be hard.

0

You can try Hibernate 4 multi tenancy feature, I have used it also. Just follow the documentation on how to configure it https://docs.jboss.org/hibernate/core/4.2/devguide/en-US/html/ch16.html

If you already use JPA, just change the JPA provider to use Hibernate. EntityManager is just a wrapper of Hibernate Session. Hibernate will switch the database connection automatically as long as you provide the implementation of CurrentTenantIdentifierResolver

MangEngkus
  • 1,863
  • 11
  • 16