Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Hibernate Session from EJB using EntityManager

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

like image 615
Bogdan Avatar asked Dec 02 '10 13:12

Bogdan


People also ask

Which method is used to access the proprietary Hibernate Session from the EntityManager API?

unwrap(Session. class)' is used to get session from EntityManager.

Does Hibernate use EntityManager?

Hibernate provides implementation of JPA interfaces EntityManagerFactory and EntityManager . EntityManagerFactory provides instances of EntityManager for connecting to same database. All the instances are configured to use the same setting as defined by the default implementation.

What is the difference between Session and EntityManager?

Session is a hibernate-specific API, EntityManager is a standardized API for JPA. You can think of the EntityManager as an adapter class that wraps Session (you can even get the Session object from an EntityManager object via the getDelegate() function).

What is SessionFactory in Hibernate with example?

The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file.


1 Answers

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

like image 67
Sean Patrick Floyd Avatar answered Oct 22 '22 13:10

Sean Patrick Floyd