我试图通过在我的应用程序中分离模式来实现多租户。在执行此操作时,我有一个Tenant
实体,其中包含String schemaName
,我有一个Singleton
Startup
EJB,可以创建一个EntityManagerFactory
的地图启动;一个工厂分配给每个Tenant
。
这是我的EJB:
@Startup
@Singleton
public class TenantManagementServiceImpl implements TenantManagementService {
private Map<Tenant, EntityManagerFactory> entityManagerFactoryMap;
@PersistenceContext
private EntityManager entityManager;
@PostConstruct
private void init()
{
buildEntityManagerFactories();
}
private List<Tenant> getAllTenants() {
return entityManager.createNamedQuery("Tenant.getAll", Tenant.class).getResultList();
}
private void buildEntityManagerFactories() {
entityManagerFactoryMap = new HashMap<>();
for (Tenant tenant : getAllTenants()) {
Map<String, String> properties = new HashMap<>();
properties.put("hibernate.default_schema", tenant.getSchemaName());
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyApp", properties);
entityManagerFactoryMap.putIfAbsent(tenant, entityManagerFactory);
}
}
@Override
public EntityManagerFactory getEntityManagerFactory(Tenant tenant) {
return entityManagerFactoryMap.get(tenant);
}
}
正在使用的NamedQuery
:
@NamedQuery(name = "Tenant.getAll", query = "SELECT t FROM Tenant t")
不幸的是,在启动时,我收到此错误:
java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"myapp-1.0-SNAPSHOT.war\".component.TenantManagementServiceImpl.START" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"myapp-1.0-SNAPSHOT.war\".component.TenantManagementServiceImpl.START: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance
Caused by: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance
Caused by: javax.ejb.EJBException: javax.persistence.PersistenceException: [PersistenceUnit: MyApp] Unable to build Hibernate SessionFactory
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: MyApp] Unable to build Hibernate SessionFactory
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target
Caused by: java.sql.SQLException: IJ031017: You cannot set autocommit during a managed transaction"}}
错误发生在这一行:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyApp", properties);
我使用this guide作为参考。我不明白为什么我收到这个错误。我正在使用WildFly 10.出了什么问题,我该如何纠正呢?
答案 0 :(得分:9)
EJB的默认事务行为是容器管理的,这意味着事务生命周期由应用程序服务器的ejb容器管理。您需要通过注释您的ejb类将其设置为bean管理,如:
@Startup
@Singleton
@TransactionManagement(value=TransactionManagementType.BEAN)
public class TenantManagementServiceImpl implements TenantManagementService {
}