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