18

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

Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
Bogdan
  • 5,248
  • 9
  • 39
  • 60

4 Answers4

26

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

Community
  • 1
  • 1
Sean Patrick Floyd
  • 284,665
  • 62
  • 456
  • 576
  • 4
    even better as explained by @Pascal Thivent in here http://stackoverflow.com/questions/3493495/getting-database-connection-in-pure-jpa-setup you can use `em.unwrap(Session.class)` direcly. – Jeremy S. Jan 19 '12 at 09:25
12

From Hibernate EntityManager docs, the preferred way of doing it is:

Session session = entityManager.unwrap(Session.class);
Mouscellaneous
  • 2,424
  • 3
  • 26
  • 37
6

As simple as:

Session session = (Session) em.getDelegate();
jpkrohling
  • 13,611
  • 1
  • 36
  • 38
6

If your EntityManager is properly injected (using @PersistenceContext) and is not null, then the following should work:

org.hibernate.Session hSession = (Session) em.getDelegate();
Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132