4

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?

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

Comments

1

I am doing it like this:

    EntityManagerFactory factory = 
    Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

    EntityManager em = factory.createEntityManager()

2 Comments

Thank you! I'm getting Exception: javax.persistence.PersistenceException: No Persistence provider for EntityManager named entityManagerFactoryA Do you know why?
Without checking your code it is impossible to know why, but most likely this is a misconfiguration issue (xml config not on classpath for ex)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.