Hibernate Tips: How to access Hibernate APIs from JPA

By Thorben Janssen

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.


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


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!


About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Books and Courses

Coaching and Consulting


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.

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}