Accessing Hibernate Session from EJB using EntityManager

Bogdan picture Bogdan · Dec 2, 2010 · Viewed 20.9k times · Source

Is it possible to obtain the Hibernate Session object from the EntityManager? I want to access some hibernate specific API...

I already tried something like:

org.hibernate.Session hSession =
   ( (EntityManagerImpl) em.getDelegate() ).getSession();

but as soon as I invoke a method in the EJB I get "A system exception occurred during an invocation on EJB" with a NullPointerException

I use glassfish 3.0.1

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Dec 2, 2010

Bozho and partenon are correct, but:

In JPA 2, the preferred mechanism is entityManager.unwrap(class)

HibernateEntityManager hem = em.unwrap(HibernateEntityManager.class);
Session session = hem.getSession();

I think your exception is caused because you are trying to cast to an implementation class (perhaps you were dealing with a JDK proxy). Cast to an interface, and everything should be fine (in the JPA 2 version, no casting is needed).