How to get jpa datasource properties from Entity Manager
Asked Answered
D

1

6

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 :-(

Dincolo answered 20/12, 2013 at 12:53 Comment(0)
S
1

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();
Spectroheliograph answered 20/12, 2013 at 13:20 Comment(4)
I 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 :-)Dincolo
@Dincolo - you could try the Connection interface, it is closer to the metal.Spectroheliograph
@Dincolo - 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 :)Spectroheliograph
Never mind :-) You were a great help. You showed me that I am at least on the right track!Dincolo

© 2022 - 2024 — McMap. All rights reserved.