在纯 JPA 设置中获取数据库连接 [英] Getting Database connection in pure JPA setup

查看:29
本文介绍了在纯 JPA 设置中获取数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 JPA 应用程序(使用 hibernate),我们需要将调用传递给需要 JDBC 数据库连接作为参数的遗留报告工具.有没有一种简单的方法可以访问 hibernate 设置的 JDBC 连接?

解决方案

不清楚您想从哪里获得这种联系.一种可能性是从 EntityManager 使用的底层 Hibernate Session 获取它.使用 JPA 1.0,您必须执行以下操作:

Session session = (Session)em.getDelegate();连接 conn = session.connection();

注意getDelegate() 不可移植,此方法的结果是特定于实现的:上述代码适用于 JBoss,对于 GlassFish,您必须对其进行调整 - 看看 使用 EntityManager.getDelegate() 时要小心.>

在 JPA 2.0 中,情况要好一些,您可以执行以下操作:

Connection 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屋!

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