且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用EntityManager从EJB访问Hibernate会话

更新时间:2022-10-23 22:29:52

Bozho partenon 是正确的,但:

在JPA 2中,首选机制是 entityManager.unwrap(class)


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

我认为你的异常是因为你试图转换到实现类而导致的(也许你正在处理使用JDK代理)。投射到界面,一切都应该没问题(在JPA 2版本中,不需要投射)。


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