为什么EntityManager的getDelegate()方法不会将EntityManagerImpl作为Hibernate中的底层对象返回?

时间:2016-03-02 10:08:44

标签: hibernate jpa entitymanager openejb

我正在将应用程序从Hibernate / OpenEJB / TomEE迁移到Hibernate / JBoss,我在运行时遇到了这个异常:

java.lang.ClassCastException: org.hibernate.internal.SessionImpl cannot be cast to org.hibernate.ejb.EntityManagerImpl

运行此代码时:

...
import javax.persistence.EntityManager;
...
@PersistenceContext(...)
protected EntityManager em;
...
EntityManagerImpl hibernateEntityManagerImpl = (EntityManagerImpl)em.getDelegate();
Session sess = hibernateEntityManagerImpl.getSession();
...

相同的代码在TomEE中运行。我不知道为什么getDelegate()方法不会将EntityManager作为底层对象返回。

注意:

  • 该应用程序之前已经使用了hibernate(带有lawer版本),我只是将它迁移到JBoss;
  • 我使用的是Hibernate 4.2.21.Final(EntityManager的相同版本);
  • persistence.xml提供程序为org.hibernate.ejb.HibernatePersistence

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

如果您正在使用JBoss EAP / Hibernate,则可以替换

EntityManagerImpl hibernateEntityManagerImpl = (EntityManagerImpl)em.getDelegate();

通过:

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

答案 1 :(得分:0)

请注意, getDelegate 方法实现是特定于提供程序的。对一个提供商有效的方法不一定适用于另一个jpa提供商。 以下是javadoc关于getDelegate()

的说法
  

返回EntityManager的基础提供程序对象,如果   可用。此方法的结果是特定于实现的。

JPA规范说明了提供商必须提供的内容以及不提供的内容。 "非强制性" jpa规范中的内容将由jpa提供商实施或赢得。

最好只使用JPA中的强制规范,因为我们的目标是减少提供程序与JPA的依赖关系。我们不应该使用提供者特定的实现。

答案 2 :(得分:0)

您没有告诉您使用哪个版本的JBoss EAP,所以我认为它是最新版本。

JBoss EAP / JBoss AS / WildFly捆绑了它自己的JBoss Hibernate。如果您的应用程序中捆绑了另一个Hibernate库,那么基于类加载配置,应用程序的类加载器可能会也可能不会使用它。

如果您的应用程序是基于Maven的,那么您应该遵循JBoss Developer指南。检查JBoss Quickstarts并相应地修改您的pom。它真的很值得,它可以为你节省很多问题。

最后,尽量避免使用专有API。每次重新键入特定实现的某个接口时,您都可能使用专有API并提出麻烦。

相关问题