Accessing Hibernate Session from EJB using EntityManager

被刻印的时光 ゝ 提交于 2019-11-30 00:17:33
Sean Patrick Floyd

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

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

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

As simple as:

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

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

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