Hibernate Tips: How to access Hibernate APIs from JPA


Take your skills to the next level!

The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, monthly Java Persistence News, monthly coding problems, and regular expert sessions.


Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.

Question:

I’m using Hibernate via the EntityManager API. Is there any way to access the proprietary Hibernate Session and SessionFactory?

Solution:

Since version 2.0, JPA provides easy access to the APIs of the underlying implementations. The EntityManager and the EntityManagerFactory provide an unwrap method which returns the corresponding classes of the JPA implementation. In the case of Hibernate, these are the Session and the SessionFactory.

You can see an example in the following code snippet.

Session session = em.unwrap(Session.class);
SessionFactory sessionFactory = em.getEntityManagerFactory().unwrap(SessionFactory.class);

In the first line, I get the current Hibernate Session from the EntityManager. I, therefore, call the unwrap method on the EntityManager and provide the Session class as a parameter.

The second line looks very similar. I get the EntityMangerFactory for the current EntityManager and call the unwrap method the Hibernate-specific SessionFactory class.

These classes provide you full access to proprietary Hibernate features, like the support for Streams and Optional.

Hibernate Tips Book

Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.

Get it now!

3 Comments

  1. Many thanks for this explanation. I was unsure how to create get the EntityManagerFactory in hibernate 5 with JPA in order to print the statistics using sessionFactory.getStatistics();

    Again, excellent article! 🙂

  2. Avatar photo Rahul Saini says:

    Hi Thorben,
    This is a fabulous, and very nice initiative that you are providing latest Hibernate and Java Cheatsheets for tricky hibernate issues along with nice Hibernate How To tips. Please keep the goodies flowing.

    With regards to Hibernate, I have a question:

    How do we map User Defined Types (which we can define in RDBMS like Oracle) in Hibernate? Please provide a cheatsheet with example for the same.

    Kudos for the work till now!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.