Home > Net >  How to get a specific EntityManager programmatically without using @PersistenceContext annotation
How to get a specific EntityManager programmatically without using @PersistenceContext annotation

Time:03-31

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?

CodePudding user response:

I am doing it like this:

    EntityManagerFactory factory = 
    Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

    EntityManager em = factory.createEntityManager()

CodePudding user response:

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?

  • Related