简体   繁体   English

如何在JPA中使用动态JNDI数据源?

[英]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. 例如, Subscription对象可能与德国或西班牙相关联。 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. 我们在jboss 5上运行,并且每个文件都有一个不同的数据源配置(* ds.xml)文件,在启动时动态生成。 They are stored in JNDI - so we have DataSourceDE, DataSourceES, etc. 它们存储在JNDI中 - 所以我们有DataSourceDE,DataSourceES等。

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. 以下是它应该如何工作:如果请求进入'为德国提取订阅17'那么我计算数据源应该是DataSourceDE并使用JPA / hibernate从正确的数据库中获取该对象。 There will be a subscription 17 in the Spanish database too, which I don't want in this example. 西班牙语数据库中也会有一个订阅17,在这个例子中我不想要。

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: 我可以自动生成persistence.xml以为数据源创建额外的持久性单元,但是Subscription类使用以下注释进行注释:

@PersistenceContext(unitName="core")

This is not going to work - how can I set the persistence context on the java object dynamically? 这不起作用 - 如何动态地在java对象上设置持久化上下文?

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. 主要思想是使用一个Stateless会话bean ,它引用了两个持久性单元。 Depending on what has to be done, this bean does a lookup to call the corresponding EntityManager . 根据必须完成的操作,此bean执行查找以调用相应的EntityManager Furthermore here: 此外:

Multi-Tenancy With EJB 3.1 and JPA 2.0 多租户使用EJB 3.1和JPA 2.0

You can change the persistence context for the EntityManager at runtime like this: 您可以在运行时更改EntityManager的持久性上下文,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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