为实体运行时动态选择数据源
我有一个实体 bean,它代表多个数据库/数据源的预期结果,也可以执行不同的查询,但总是返回相同的结果。因此,该 bean 可以在应该能够动态选择的不同数据源上重复使用。
JPA 是否可以在运行时选择用于执行查询的数据源,并返回相同类型的实体 bean? 另外,我的 ejb/应用程序是否需要定义将使用的数据源?或者我总是可以通过 jndi 指定要使用的数据源?每次创建新数据源时都修改描述符并重新部署应用程序不是一种选择。
抱歉,如果这个问题没有 100% 有意义,那么很难理解这个想法。
I have an entity bean that will represent an expected result over multiple databases/datasources and can also be different queries executed, but same result always comming back. So the bean is re-used over different datasources that should be able to be dynamicly selected.
Is it possible with JPA to select during runtime the data source to be used to execute a query, and return the same type of entity bean?
Also, does my ejb/application need to define the datasources that will be used? Or can I always specify via jndi what datasource to use? Modifying the descriptor's and re-deploying an application everytime a new datasource is created is not an option.
Sorry if the question does not make 100% sense, rather difficult to get the idea through.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法在运行时更改持久性单元的数据源。但是,您可以配置多个持久性单元并使用一个或另一个
EntityManagerFactory
。也许 JPA 不是适合您的用例的工具。应用程序如何知道“可用数据源”?
You can't change the datasource of a persistence unit at runtime. However, you can configure several persistence unit and use one or another
EntityManagerFactory
. Maybe JPA is not the right tool for your use case.And how will the application be aware of the "available datasources"?
您可以在运行时更改 JPA 数据源,但该方法很棘手(内省、特定于 JPA 实现,...)。
我已经实现了自己的 javax.persistence.spi.PersistenceProvider 实现,它覆盖了 org.hibernate.ejb.HibernatePersistence 并在两个 Map 中设置了数据源在创建
EntityManagerFactory
之前,获取PersistenceProvider
的 和PersistenceUnitInfo
。这样,我的 EntityManagerFactory 就有了一个在运行时配置的数据源。我会保留我的EntityManagerFactory
直到应用程序被取消部署。您可以使用相同的方法并创建 N 个不同的 EntityManagerFactory,每个都有其特定的数据源。但请记住,每个
ÈntityManagerFactory
都会使用大量内存。You can change the JPA datasource at runtime, but the approach is tricky (introspection, JPA implementation specific, ...).
I've implemented my own implementation of
javax.persistence.spi.PersistenceProvider
which override theorg.hibernate.ejb.HibernatePersistence
and sets the datasource in both theMap
andPersistenceUnitInfo
of thePersistenceProvider
just before creating theEntityManagerFactory
. This way, myEntityManagerFactory
has a datasource which has been configured at runtime. I keep myEntityManagerFactory
until the application is undeployed.You could use the same be approach and create N different
EntityManagerFactory
, each with its specific datasource. However keep in mind that eachÈntityManagerFactory
uses a lot of memory.