It has been almost 3 years, so I suppose there is no easy way to do so. I'm closing this question. If anyone finds solution in the future, you may post answer and I will re-check the correct answer.
JPA entity manager from Datasource during runtime
-
29-05-2022 - |
Question
I'm wondering if there is possibility to create EntityManager from defined datasource in AS during runtime via JNDI lookup. Imagine that administrator configures a new datasource within the AS (TomEE, JBoss, Glassfish... it could be any JEE6 AS) and I want to use this datasource only by providing JNDI name of this datasource in my application.
String datasourceName = "java:/myDS";
Datasource/Resource datasource = // some JNDI lookup via datasourceName
EntityManager em = // some magic, maybe with EntityManagerFactory
Note that it would be nice to stay in Java EE 6 specification and not use any vendor specific implementation.
Solution
OTHER TIPS
I suggest to create two entityManagerFactory object and inject properties using @PersistenceUnit(unitName='') and create entityManager from factory object and use within a transaction context and then clear it.
Class EntityManagerProducer{
@PersistenceUnit(unitName='')
EntityManagerFactory emf1;
@PersistenceUnit(unitName='')
EntityManagerFactory emf2;
EntityManager getEm1()
{
return emf1.createEntityManager();
}
EntityManager getEm2()
{
return emf2.createEntityManager();
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow