Accessing Hibernate Session from EJB using EntityManager

余生颓废 提交于 2019-12-29 18:42:47

问题


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


回答1:


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




回答2:


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

Session session = entityManager.unwrap(Session.class);



回答3:


As simple as:

Session session = (Session) em.getDelegate();



回答4:


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

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


来源:https://stackoverflow.com/questions/4335570/accessing-hibernate-session-from-ejb-using-entitymanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!