如何以编程方式检索持久性单元使用的数据源 [英] How to retrieve the datasource used by a persistence unit programmatically
问题描述
...没有真正阅读和解析 persistence.xml
我可以检索使用 EntityManager 的持久性单元%28%29>它的工厂属性。我可以使用 jboss-as-controller-client 检索可用的数据源。但是我没有找到API来给我一个特定 EntityManager
的数据源。
A String
带一个名字就足够了。
谢谢
I我正在使用Hibernate 4.0.1.Final通过JPA 2在JBoss 7.1.1.Final上。
编辑:我想避免从JPA转移到Hibernate API如果可能的话。
编辑:奥古斯托的解决方案工作,我有一些关于细节的注释:由于 ClassCastException
:( org.jboss.as.jpa.container.TransactionScopedEntityManager无法转换为org.hibernate.ejb.EntityManagerImpl
),但它适用于检索到的工厂。所以我省略了步骤1.
我也找不到从实例中检索数据源名称的方法。所以我不得不满足目录名: connectionProvider.getConnection()。getCatalog();
您需要:
- 转换
EntityManager
到EntityManagerImpl
(Hibernate实现) - 调用
getFactory()
- 将code> EntityManagerFactory 转换为
HibernateEntityManagerFactory
- 调用
getSessionFactory()
并将其转换为SessionFactoryImpl
- code> getConnectionProvider()并将其转换为正确的实现。您可以在这里看到 的实现。我假设它是
DatasourceConnectionProvider
- 调用
getDataSource()
和您完成了。
不幸的是,您必须使用Hibernate API,因为无法使用JPA API检索DataSource。
...without actually reading and parsing the persistence.xml
I can retrieve the name of the persistence unit of an EntityManager
using the properties of it's factory. I can retrieve the available datasources using the jboss-as-controller-client. But I have found no API that would give me the datasource of a particular EntityManager
.
A String
with a name would be enough.
Thank you
I am working with Hibernate 4.0.1.Final over JPA 2 on a JBoss 7.1.1.Final.
EDIT: and I would like to avoid straying from JPA to Hibernate APIs if possible.
EDIT : Augusto's solution worked, I have some notes on details: The casting of the EM didn't work because of a ClassCastException
:(org.jboss.as.jpa.container.TransactionScopedEntityManager cannot be cast to org.hibernate.ejb.EntityManagerImpl
), but it worked for the retrieved factory. So I omitted step 1.
I also could not find a way to retrieve the name of the datasource from the instance. So I had to content myself with the catalog name: connectionProvider.getConnection().getCatalog();
You need to:
- cast the
EntityManager
toEntityManagerImpl
(the Hibernate implementation) - call
getFactory()
- cast the
EntityManagerFactory
toHibernateEntityManagerFactory
- call
getSessionFactory()
and cast it toSessionFactoryImpl
- call
getConnectionProvider()
and cast it to the correct implementation. You can see the implementations here. I'll assume that it's aDatasourceConnectionProvider
- call
getDataSource()
and you're done.
Unfortunately, you must use the Hibernate API, as there's no way to retrieve the DataSource using the JPA API.
这篇关于如何以编程方式检索持久性单元使用的数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!