hibernatejakarta-eejpajpa-2.0jboss7.x

How to retrieve the datasource used by a persistence unit programmatically


...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();


Solution

  • You need to:

    1. cast the EntityManager to EntityManagerImpl (the Hibernate implementation)
    2. call getFactory()
    3. cast the EntityManagerFactory to HibernateEntityManagerFactory
    4. call getSessionFactory() and cast it to SessionFactoryImpl
    5. call getConnectionProvider() and cast it to the correct implementation. You can see the implementations here. I'll assume that it's a DatasourceConnectionProvider
    6. 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.