Hi,
if you know the JNDI names of the datasources that you want to switch between, you can do it like this:
private Map<String, EntityManager> cachedEntityManagerMap = new HashMap<String, EntityManager>(); // cached EntityManagers
private EntityManager getEntityManager() {
String jndiName = "java:/something/someDS"; // TODO: Here you need to determine the JNDI name of the DataSource you want to switch to!
log.info( "Change datasource to '" + jndiName + "'" );
if( cachedEntityManagerMap.containsKey( jndiName ) ) { // if already created, return a cached version instead of creating a new
log.debug( "Return cached EntityManager with jndiName '" + jndiName + "'" );
return cachedEntityManagerMap.get( jndiName );
} else {
log.debug( "Return new EntityManager with jndiName '" + jndiName + "'" );
/*
* See "Hibernate Entity Manager User Guide", chapter "Bootstrapping" for more examples of what to override in
* the map
*/
Map<String, String> emMap = new HashMap<String, String>();
emMap.put( "javax.persistence.jtaDataSource", jndiName );
EntityManager em = Persistence.createEntityManagerFactory( "somePU", emMap )
.createEntityManager();
cachedEntityManagerMap.put( jndiName, em );
return em;
}
private EntityManager getEntityManager() {
String jndiName = "java:/something/someDS"; // TODO: Here you need to determine the JNDI name of the DataSource you want to switch to!
log.info( "Change datasource to '" + jndiName + "'" );
if( cachedEntityManagerMap.containsKey( jndiName ) ) { // if already created, return a cached version instead of creating a new
log.debug( "Return cached EntityManager with jndiName '" + jndiName + "'" );
return cachedEntityManagerMap.get( jndiName );
} else {
log.debug( "Return new EntityManager with jndiName '" + jndiName + "'" );
/*
* See "Hibernate Entity Manager User Guide", chapter "Bootstrapping" for more examples of what to override in
* the map
*/
Map<String, String> emMap = new HashMap<String, String>();
emMap.put( "javax.persistence.jtaDataSource", jndiName );
EntityManager em = Persistence.createEntityManagerFactory( "somePU", emMap )
.createEntityManager();
cachedEntityManagerMap.put( jndiName, em );
return em;
}
}