Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get jpa datasource properties from Entity Manager

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

like image 856
Stoffelchen Avatar asked Dec 20 '13 12:12

Stoffelchen


People also ask

How do I get JPA EntityManager?

How to access JPA Entity Manager? We can inject an EntityManager object in a Spring Bean such as repository, service or controller… using @Autowired annotation. Spring Data JPA will initialize EntityManagerFactory for default persistence unit at runtime.

How does EntityManager work in JPA?

In JPA, the EntityManager interface is used to allow applications to manage and search for entities in the relational database. The EntityManager is an API that manages the lifecycle of entity instances. An EntityManager object manages a set of entities that are defined by a persistence unit.


1 Answers

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();
like image 193
kostja Avatar answered Sep 19 '22 14:09

kostja