Is it possible to use the configuration from persistence.xml?

I have one persistence unit configured in my persistence.xml, but I have two databases. These databases are identical in terms of schema. I am trying to do the following:

Persistence.createEntityManagerFactory("unit", primaryProperties);
Persistence.createEntityManagerFactory("unit", secondaryProperties);

The properties contain different connection settings (user, password, jdbc url, ...).
I actually tried this, and it seems that hibernate (my jpa provider) returns the same instance in the second call, without worrying about properties.

Do I need to copy the configuration to the second block?


I nailed it to something other than I thought before. EntityManagers (and factories) returned by the above calls work as expected, but problem getDelegate(). I need the base session to support legacy code in my application, which directly depends on the hibernate api. I have done this:

final Session session = (Session) manager.getDelegate();

But somehow I get a session working in the primary database even when using the entitymanager that works with the second.

+3
source share
1 answer

This is strange. According to sources HibernateProvider#createEntityManagerFactory, the method returns a new instance:

public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) {
    Ejb3Configuration cfg = new Ejb3Configuration();
    Ejb3Configuration configured = cfg.configure( persistenceUnitName, properties );
    return configured != null ? configured.buildEntityManagerFactory() : null;
}

And I definitely don't get the same instances in this dummy test:

@Test
public void testCreateTwoDifferentEMF() {
    Map properties1 = new HashMap();
    EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("MyPu", properties1);
    Map properties2 = new HashMap();
    properties2.put("javax.persistence.jdbc.user", "foo");
    EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("MyPu", properties2);
    assertFalse(emf1 == emf2); //passes
}

, ( ).

+3

Source: https://habr.com/ru/post/1762512/


All Articles