如何从实体管理器获取JPA数据源属性 [英] How to get jpa datasource properties from Entity Manager

查看:122
本文介绍了如何从实体管理器获取JPA数据源属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以通过实体管理器获取数据库连接属性.

I was wondering if it's possible to get database connection properties through entity manager.

我的persistence.xml看起来像这样

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>

我想要类似的东西

String host = em.getSomeFunction().getProperties().get("server");
String database = em.getSomeFunction().getProperties().get("database");
or
String url = em.getSomeFunction().getConnectionPool().getURL();

其中url类似于jdbc:oracle:thin:@1.2.3.4:5678:database. 我正在将JDeveloper 12c与EclipseLink,Oracle数据库和NO Hibernate一起使用.

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?

亲切的问候,

Stefi

@Kostja:再次感谢您的帮助,但是正如我在帖子中提到的,我根本不使用Hibernate.

@Kostja: thx again for your help but as I mentioned in my post I do not use Hibernate at all.

我已经试图像这样使用Connection.class

I already tried to use the Connection.class like this

java.sql.Connection conn = em.unwrap(java.sql.Connection.class);

来自此处.在此语句中,我总是为Connection以及getSession()获得一个NPE

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

来自此处.

我很困惑为什么这些解决方案对我有用.也许我缺少了一些东西:-(

I'm quiet confused why any of these solutions work for me. Maybe I'm missing something :-(

推荐答案

使用JPA可以使用的最远的方法是查询 Connection .可用属性的列表在提供程序之间以及单个提供程序的不同版本之间有所不同.

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.

像这样访问EMF的属性:

Access the properties of the EMF like this:

Map<String,Object> props = emf.getProperties();

动手使用Connection会涉及更多点,并且取决于JPA的实现.这可能适用于Hibernate,礼貌@Augusto :

Getting your hands on the Connection is a bit more involved and depends on the JPA implementation. This could work for Hibernate, courtesy @Augusto:

EntityManagerFactory投射到HibernateEntityManagerFactory, 调用getSessionFactory()并将其转换为SessionFactoryImpl,然后调用getConnectionProvider()

cast the EntityManagerFactory to HibernateEntityManagerFactory, call getSessionFactory() and cast it to SessionFactoryImpl, call getConnectionProvider()

connectionProvder.getConnection();

这篇关于如何从实体管理器获取JPA数据源属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆