JPA-是否有方法/方法来检索持久性单元信息 [英] JPA - Is there a way/method to retrieve Persistence Unit information

查看:74
本文介绍了JPA-是否有方法/方法来检索持久性单元信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在代码中找出我的数据源名称.有办法吗? 我正在使用eclipselink.

I'd like to find out my data source name in the code. Is there a way of doing that? I am using eclipselink.

谢谢 更具体地说,我的目标是获得一个jdbc连接对象. 我知道我可以通过以下方式做到这一点:

thanks To be more specific, my aim is to get an jdbc connection object. I know i can do that thru:

datasource = (DataSource) (new InitialContext()).lookup("my_data_source_name")
connection = dataSource.getConnection();

但是我不想在代码中对数据源名称进行硬编码.

But I don't want to hard code the data source name in my code.

我也尝试过

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

,它总是返回null.

and it always return null.

推荐答案

.unwrap()应该是方法,如在调用em.unwrap(java.sql.Connection.class);时,我还经常得到null,因为它不在交易之内.当这样调用时:

I also used to get null when calling em.unwrap(java.sql.Connection.class); because it was not inside a transaction. When called like this:

em.getTransaction().begin();
java.sql.Connection conn = em.unwrap(java.sql.Connection.class);
// ...
em.getTransaction().commit();

一切正常!

这篇关于JPA-是否有方法/方法来检索持久性单元信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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