EntityManagerFactoryWrapper无法强制转换为SessionFactoryImplementor

问题描述

我正在尝试在Java ee 7上学习jpa multitenant。我正在关注本教程。

https://developers.redhat.com/blog/2020/06/15/jakarta-ee-multitenancy-with-jpa-on-wildfly-part-1/

但是我遇到了以下错误

at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:748)
Caused by: javax.ejb.TransactionRolledbackLocalException: Exception thrown from bean
at com.sun.ejb.containers.EJBContainerTransactionManager.checkExceptionClientTx(EJBContainerTransactionManager.java:662)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
... 125 more
Caused by: java.lang.classCastException: com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper cannot be cast to org.hibernate.jpa.internal.EntityManagerFactoryImpl
at net.rhuanrocha.dao.Dao.getEntityManager(Dao.java:21)
at net.rhuanrocha.dao.JobDao.findAll(JobDao.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

在Dao.java内部-> getEntityManager()

我的Maven依赖项如下:

  1. 提供了javax javaee-web-api 7.0
  2. org.hibernate hibernate-entitymanager 5.0.7。最终jar

我正在使用Glassfish 4.1作为服务器和JDK 8。 导入如下:

  1. 导入org.hibernate.engine.spi.SessionFactoryImplementor;
  2. 导入org.hibernate.jpa.internal.EntityManagerFactoryImpl;
  3. 导入javax.persistence.EntityManagerFactory;
  4. 导入javax.persistence.PersistenceUnit;
  5. 导入javax.persistence.EntityManager;

解决方法

这有效。我使用的后端是 Jakarta EE 8、Hibernate 5.4 和 Payara 2021。我认为你的版本应该也可以。

import com.dao.multitenancy.MultitenancyResolver;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
//import org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl;
import org.hibernate.engine.spi.SessionFactoryImplementor;

/**
 *
 * @author Peter
 */
public abstract class Dao {

    @PersistenceUnit
    private EntityManagerFactory emf;

    public EntityManager getEM(final String tenantId) {

        //EntityManagerFactory entityManagerFactory = entityManagerFactory();
       final SessionFactoryImplementor sf = emf.unwrap(SessionFactoryImplementor.class);
          
        final MultitenancyResolver tenantResolver = (MultitenancyResolver) sf.getCurrentTenantIdentifierResolver();
        tenantResolver.setTenantIdentifier(tenantId);

        return emf.createEntityManager();
    }

}

参考:https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#events-interceptors