3

Is there a way that I can get JPA (Eclipselink specifically) to dynamically select a connection pool depending on some property bound to the current thread?

The problem I'm trying to solve is scaling a multitenant system, where tenants may be split up over several DB instances. Each DB instance will be multitenant, but to scale, I may not be able to fit all tenants in one DB instance comfortably.

I am familiar with @Multitenant to support single-table multitenancy, and have successfully used Eclipselink session event callbacks to set values in the Eclipselink Session dynamically. I'm trying to take the next step of changing the DataSource that the EntityManager will be using, so I don't have to necessarily use a clustered DB.

Thanks!

wrschneider
  • 17,913
  • 16
  • 96
  • 176

3 Answers3

0

Take a look at this

http://code.google.com/p/jdbc-helper/wiki/LoadBalancingDataSource

It creates a datasource that loadbalances to backend datasources.

  • 2
    unfortunately i'm not just trying to load balance, I'm trying to explicitly specify a target datasource depending on some attribute of the current request/thread. – wrschneider Jul 15 '12 at 01:56
  • extend LoadBalancingDataSource and override getConnection to select the specific connectionPool from connectionPools based on a threadlocal variable. I haven't worked with the LoadBalancingDataSource so I cannot vouch for its quality. – Erik Martino Hansen Aug 07 '12 at 06:14
  • 1
    Be aware of the Eclipselink shared 2nd level cache, it might get poisoned by inconsistent databases – Erik Martino Hansen Aug 07 '12 at 06:16
0

You can use an EntitiyManagerFactory which allows the creation of an EntitiyManager for a specific datsasource (via a String property) as explained under

http://foobar.lu/wp/2010/12/30/change-jpa-entitymanager-connection-properties-at-runtime/

weaselflink
  • 244
  • 2
  • 7
  • 1
    I am using `@PersistenceContext` injection for my `EntityManager` and would like to keep it that way. I don't want to manage creating and closing EntityManagers in my application code. If you knew how to do exactly the same thing via EclipseLink session callbacks that would be ideal. – wrschneider Jul 20 '12 at 14:21
  • @wrschneider were you able to get a solution . I am also facing the same scneario and would like to understand if you were able to achieve it using PersistenceContext or Persistence-Unit – vignesh787 Mar 20 '19 at 05:52
0

You might want to check this post. It might be helpful or give you a clue on how to achieve your solution.

Community
  • 1
  • 1
Uchenna Nwanyanwu
  • 3,174
  • 3
  • 35
  • 59
  • 1
    that could work for switching schemas / databases in a single installation/instance, but it would not allow me to dynamically select a host. – wrschneider Jul 23 '12 at 19:55