I am trying to implement multi-tenancy by sharing schemas in my application. In doing so, I have an object Tenantthat contains String schemaName, and I have an Singleton StartupEJB that creates a map EntityManagerFactoryat startup; one factory assigned to each Tenant.
Here is my 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);
}
}
And used NamedQuery:
@NamedQuery(name = "Tenant.getAll", query = "SELECT t FROM Tenant t")
Unfortunately, when I start, I get this error:
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"}}
The error in this line is:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyApp", properties);
I use this guide as a reference. I do not understand why I am getting this error. I am using WildFly 10. What is going wrong and how can I fix it?