I have two different EntityManagers I want to use in a legacy class (no bean) from its related EntityManagerFactory
@PersistenceContext(name = "entityManagerFactoryA") 
EntityManager entityManagerA;
@PersistenceContext(name = "entityManagerFactoryB") 
EntityManager entityManagerB;
I've tried to use getBean()
ApplicationContext applicationContext;
applicationContext.getBean("entityManagerFactoryA");
which results in this error:
Cannot cast 'com.sun.proxy.$Proxy167' to 'java.persistence.EntityManager'
So currently wrapping the usual injection via @PersistenceContext into a wrapper bean, which then is fetched from the ApplicationContext works
@Getter
@Component
private class EntityManagerAWrapper {
     @PersistenceContext(name = "entityManagerFactoryA")
     EntityManager entityManagerA;
}
.
.
.
applicationContext.getBean(EntityManagerAWrapper.class).getEntityManagerA();
This however is an unnesessary "hack" that I want to avoid. Is there any chance to get the correct EntityManager in a simpler way?
I've come up with new working solution:
EntityManager em = context.getBeansOfType(LocalContainerEntityManagerFactoryBean.class)
                          .getOrDefault("&entityManagerFactoryA", null)
                          .getNativeEntityManagerFactory()
                          .createEntityManager();
For some reason I need to prefix EntityManagerFactory key (name) with &. I would appreciate any explanation why is this required?
I am doing it like this:
    EntityManagerFactory factory = 
    Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With