How to get jpa datasource properties from Entity Manager
The farthest you can go with JPA is to query the properties of the EntityManagerFactory
or the Connection
. The list of available properties varies between providers and between different version of a single provider.
Access the properties of the EMF like this:
Map<String,Object> props = emf.getProperties();
Getting your hands on the Connection
is a bit more involved and depends on the JPA implementation. This could work for Hibernate, courtesy @Augusto:
cast the EntityManagerFactory
to HibernateEntityManagerFactory
,
call getSessionFactory()
and cast it to SessionFactoryImpl
, call getConnectionProvider()
connectionProvder.getConnection();
Stoffelchen
Updated on June 24, 2022Comments
-
Stoffelchen almost 2 years
Hi everybody
I was wondering if it's possible to get database connection properties through entity manager.
My persistence.xml looks like this
<persistence ...> <persistence-unit name="default" transaction-type="JTA"> <jta-data-source>DatasourceForTestSystem</jta-data-source> <class> some.package.and.some.Class </class> ... </persistence-unit> </persistence>
I want something like
String host = em.getSomeFunction().getProperties().get("server"); String database = em.getSomeFunction().getProperties().get("database"); or String url = em.getSomeFunction().getConnectionPool().getURL();
where url is something like
jdbc:oracle:thin:@1.2.3.4:5678:database
. I'm using JDeveloper 12c with EclipseLink, an Oracle database and NO Hibernate.Does somebody know how to get information about the connection properties?
Kind regards,
Stefi
-- UPDATE --
@Kostja: thx again for your help but as I mentioned in my post I do not use Hibernate at all.
I already tried to use the Connection.class like this
java.sql.Connection conn = em.unwrap(java.sql.Connection.class);
from here. I always got a NPE for the Connection as well as for getSession() in this statement
((JNDIConnector)em.unwrap(JpaEntityManager.class) .getSession().getLogin().getConnector()).getName();
from here.
I'm quiet confused why any of these solutions work for me. Maybe I'm missing something :-(
-
Stoffelchen over 10 yearsI already tried this and only got three properties. None of them contained the neccessary information. That's why I was wondering if there is any other way to get host, port, database user or what else from Entity Manager :-( But thanks anyway for your help :-)
-
kostja over 10 years@Stoffelchen - you could try the
Connection
interface, it is closer to the metal. -
kostja over 10 years@Stoffelchen - my apologies for being less than helpful. I will leave my answer here as a warning for the posterity - this does not work. Do post and accept your solution once you have found one. You got my vote :)
-
Stoffelchen over 10 yearsNever mind :-) You were a great help. You showed me that I am at least on the right track!