在纯JPA设置中获取数据库连接 [英] Getting Database connection in pure JPA setup
问题描述
我们有一个JPA应用程序(使用hibernate),我们需要将一个调用传递给需要JDBC数据库连接作为参数的传统报告工具。有没有一种简单的方法可以访问Hibernate已经设置的JDBC连接?
解决方案你想获得连接的位置不清楚。一种可能性是从 EntityManager
使用的底层Hibernate Session
中获取它。使用JPA 1.0,您必须执行以下操作:
会话会话=(会话)em.getDelegate();
Connection conn = session.connection();
请注意, getDelegate()
不可移植,结果这个方法是特定于实现的:上面的代码在JBoss中工作,对于GlassFish你必须适应它 - 看看时要小心。
在JPA 2.0中,事物
$ b
连接conn = em.unwrap(Session.class).connection() ;
如果您在一个容器中运行,您还可以对配置的 DataSource
。
We have a JPA application (using hibernate) and we need to pass a call to a legacy reporting tool that needs a JDBC database connection as a parameter. Is there a simple way to get access to the JDBC connection hibernate has setup?
Where you want to get that connection is unclear. One possibility would be to get it from the underlying Hibernate Session
used by the EntityManager
. With JPA 1.0, you'll have to do something like this:
Session session = (Session)em.getDelegate();
Connection conn = session.connection();
Note that the getDelegate()
is not portable, the result of this method is implementation specific: the above code works in JBoss, for GlassFish you'd have to adapt it - have a look at Be careful while using EntityManager.getDelegate().
In JPA 2.0, things are a bit better and you can do the following:
Connection conn = em.unwrap(Session.class).connection();
If you are running inside a container, you could also perform a lookup on the configured DataSource
.
这篇关于在纯JPA设置中获取数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!