Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...