简体   繁体   中英

how can I use my dynamic JNDI datasources with JPA?

We have an application which uses multiple databases to store the same data for different countries.

For example a Subscription object might be associated with Germany or Spain. If it's a German subscription, it needs to be stored in a different database to the Spanish subscriptions. The databases are identical in structure, but they have different contents.

We are running on jboss 5, and have a different datasource config (*ds.xml) file for each one, generated dynamically at startup. They are stored in JNDI - so we have DataSourceDE, DataSourceES, etc.

Here's how it should work: if a request comes in saying 'fetch subscription 17 for Germany' then I calculate that the datasource should be DataSourceDE and use JPA / hibernate to go fetch that object from the correct database. There will be a subscription 17 in the Spanish database too, which I don't want in this example.

I can generate the persistence.xml automatically to create the extra persistence units for the datasources, but the Subscription class is annotated with the following:

@PersistenceContext(unitName="core")

This is not going to work - how can I set the persistence context on the java object dynamically?

What you are trying to achieve is known as Multi-Tenancy . Here is a perfectly suitable tutorial for your question to make it work.

The main idea is to use a Stateless session bean which has a reference to both persistence units. Depending on what has to be done, this bean does a lookup to call the corresponding EntityManager . Furthermore here:

Multi-Tenancy With EJB 3.1 and JPA 2.0

You can change the persistence context for the EntityManager at runtime like this:

EntityManagerFactory emf = 
    Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM