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
unwrap(Session. class)' is used to get session from 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.
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).
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With