How to get Session object from JPA EntityManager
Need to tap into Hibernate‑specific APIs like the criteria engine, cache control, or `session.evict()`? In this quick tip, I’ll show you how to unwrap the native Hibernate Session from your injected EntityManager.
Steps:
// 1. Inject the JPA EntityManager @Inject
private EntityManager entityManager; // javax.persistence.EntityManager
// 2. Unwrap the native Hibernate Session
Session session = entityManager.unwrap(Session.class); // org.hibernate.Session
One thing to keep in mind: `unwrap()` throws `PersistenceException` if Hibernate isn't the underlying provider or if the persistence context isn't active. With older Hibernate versions, you might see `entityManager.getDelegate()` still used, but that method is deprecated in JPA 2.0 – stick with `unwrap()` for any modern project.