0

I need to switch the database dynamically on my application in runtime. So a do this class to producer my own entitymanager:

@ApplicationScoped
public class ApplicationResources {

    @PersistenceContext
    private EntityManager entityManager;

    @Produces
    @Default
    @RequestScoped
    public EntityManager produceEntityManager() {
        Map<Object, Object> props = new HashMap<Object, Object>();
        props.put(PersistenceUnitProperties.JTA_DATASOURCE, DATABASENAME);
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PU", props);
        return  entityManagerFactory.createEntityManager();
    }

    public void dispose(@Disposes EntityManager entityManager) {
        entityManager.close();
    }
}

So I use @Inject to get a entityManager and do all the persistence operations on database. I have two problems:

  • When I change the jta-data-source the Eclipselink takes a lot of time to connect. And its run all validations again (like in application startup). I need to change connection more fast.
  • I can't save or update objects when I'm logged in. I can update and get them all (objects) just it.

I used this approach for seeming simpler. Because my application is already quite large. And now I need multiple clients in other databases. Help me there .. maybe this could be very wrong, but the multitenancy approaches with eclipselink seemed very complex. I need the idea of multitenancy with a bunch of different data. But if I could only change the connected database when and where I wanted, it would solve a lot.

I am using the Wildfly Server, CDI, Eclipselink, JTA and JSF.

Thank you for your help.

Eduardo
  • 3
  • 1
  • 4
  • 1
    Why not use 2 EntityManager? – jklee Dec 10 '16 at 13:01
  • Because I have N databases... I can't add a new entity manager every time that I have a new client. This is why I'm trying to create entity managers dynamically. – Eduardo Dec 11 '16 at 17:41
  • I'm not sure but think the property validation-only will help. You also need target-database. http://www.eclipse.org/eclipselink/documentation/2.6/jpa/extensions/persistenceproperties_ref.htm#validation-only – Jaqen H'ghar Dec 11 '16 at 19:08
  • @JaqenH'ghar Thanks a lot, this works properly! I just had problems with some errors but after removing the ditectory $JBOSS/standalone/data/tx-object-store like in this [question](http://stackoverflow.com/questions/6490328/what-causes-arjuna-1603-could-not-find-new-xaresource-to-use-for-recovering-non) everything works great . So now I have the second problem yet, I can't add and remove objects in my database anymore. – Eduardo Dec 12 '16 at 11:10
  • I solved the problem! I just needed to add `entityManager.joinTransaction();` on my save, update and delete methods... so that's all :) – Eduardo Dec 12 '16 at 16:15

0 Answers0