Tip

How to get the Hibernate Session from the JPA 2.0 EntityManager

This tip shows you how to get the Hibernate Session from the JPA EntityManager so you can perform functions only available from the JBoss Hibernate project.

With so many benefits and drawbacks to using either the Hibernate Session or the JPA EntityManager for performing object relational mapping, it is no wonder why enterprise architects have such a difficult time choosing between them. The JPA EntityManager is part of the Java Persistence API standard. However, the Hibernate Session provides many features that go above and beyond the JPA specification, with Criteria query capabilities being a compelling legacy feature that JPA 1.0 did not have, and Hibernate Envers being a compelling reason to use the Hibernate 4.0 Session object over its JPA brethren.

According to Emmanuel Bernard, a data architect for JBoss who is part of the Hibernate team, the preferred option for organizations adopting Hibernate to perform ORM tasks is to use the JPA EntityManager. So what should IT developers do if they need to get to the underlying Hibernate Session to access its extra features? Fortunately,  Hibernate with the JPA specification makes it possible to access the underlying Hibernate Session, even if your application is using the JSR-317 standard.

JPA 1.0 access to the Hibernate Session

To obtain the Hibernate Session from a JPA 1.0 EntityManager, the following code would be required:

org.hibernate.Session hibernateSession = (Session)entityManager.getDelegate();

Unfortunately, this syntax isn't completely portable, as this code works fine on a JBoss Application Server, but will have unpredictable results when run on other platforms.

JPA 2.0 access to the Hibernate Session

Fortunately, JPA 2.0 provides a better, more portable and more cross-platform approach to obtaining the Hibernate Session. The code to do so is as follows:

Session session = entityManager.unwrap(org.hibernate.Session.class);

And that's it! That's how easy it is to obtain the underlying Hibernate implementation class when working with the JPA EntityManager. So make this code a part of your HibernateUtil class, and make it possible for the persistence store that is working with your entity beans to morph into a Hibernate Session, allowing you to take advantage of the many neat features that go above and beyond the standard JPA specification.

Next Steps

What is the difference between Hibernate and JPA?

What is the difference between Hibernate and JDBC?

What is the difference between JDBC and ODBC?

Five interesting JDBC facts

Dig Deeper on Core Java APIs and programming techniques

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close