How to inject persistence context to different data source programmatically

Primk picture Primk · Feb 24, 2011 · Viewed 21.2k times · Source

In standard EJB 3, when injecting entity manager, persistence unit (which refers to datasource) is hardcoded into annotation: (or alternatively xml file)

@PersistenceContext(unitName = "myunit")
private EntityManager entityManager;

Is there a way to use an entity manager but to select data source by name at runtime?

Answer

Monnie picture Monnie · Feb 16, 2012

Using EclipseLink, You can set a DataSource configured in your app server.

import org.eclipse.persistence.config.PersistenceUnitProperties;
...


....
Map props = new HashMap();  
props.put(PersistenceUnitProperties.JTA_DATASOURCE, "dataSource");  
EntityManagerFactory  emf = Persistence.createEntityManagerFactory("UNIT_NAME", props);
EntityManager em = emf.createEntityManager();

PU_NAME refers to the name used in the file persistence.xml
dataSource refers name used in the app server for the jdbc Resource as "jdbc/sample"