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.
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.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
Hibernate Tips Book
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 as a paperback, ebook or PDF.