How to get the Hibernate Session from the JPA 2.0 EntityManager

Java EE development and enterprise Java platforms

How to get the Hibernate Session from the JPA 2.0 EntityManager

By Lukas Stewart

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, 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.

30 Jun 2013

Related Content

Related Resources

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.