views:

130

answers:

2

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?

+1  A: 

Hibernate uses a ConnectionProvider internally to obtain connections. From the hibernate javadoc:

The ConnectionProvider interface is not intended to be exposed to the application. Instead it is used internally by Hibernate to obtain connections.

The more elegant way of solving this would be to create a database connection pool yourself and hand connections to hibernate and your legacy tool from there.

Kees de Kooter
but it is exposed to the application... (: I think that might be the answer.
Jacob
+2  A: 

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.

Pascal Thivent
When I do either of these I get a deprecation warning. I can live with it if a have to but its a bit annoying (: Its not like I want to have to do this, its just pragmatically the simplest way to get things going.
Jacob
Yes, `connection()` is deprecated in Hibernate 3.x, they are changing the API (and I don't think you'll like the new API for your use case). But the change is planned for Hibernate 4.x, this gives you some time.
Pascal Thivent