0

I have an application that uses many databases of many types(Mysql, Postgres...). I'm in a section of the application where it would be useful to be able to return the correct EntityManager from a function that takes as a parameter a database ID.

So I tried like this:

EntityManager entityManager = (EntityManager) ApplicationContextUtil.getBean("admindb2EntityManagerFactory");

whenre ApplicationContextUtil is a class I adapted from here and looks like this:

@Component
public class ApplicationContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;
    public static ApplicationContext getContext() {
        return context;
    }
    public static Object getBean(String bean) {
        return getContext().getBean(bean);
    }    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}

But the error is:

java.lang.ClassCastException: class jdk.proxy2.$Proxy93 cannot be cast to class javax.persistence.EntityManager (jdk.proxy2.$Proxy93 is in module jdk.proxy2 of loader 'app'; javax.persistence.EntityManager is in unnamed module of loader 'app'

I know the name of the bean(admindb2EntityManagerFactory) is correct, I can inject this name in the constructor and then I can successfully use this EntityManager like here.

    private final EntityManager admindb2EntityManagerFactory;

    @Autowired
    public GenericDB(@Qualifier("admindb2EntityManagerFactory") EntityManager admindb2EntityManagerFactory) {
        this.admindb2EntityManagerFactory = admindb2EntityManagerFactory;
....

But I can't switch between many entity managers. I could declare a EntityManager for each database and switch between them with an "if" but I don't know why the solution with getBean is not working.

Victorqedu
  • 484
  • 4
  • 20

0 Answers0