JBoss Community

Re: Dinamically switch DataSource in EJB3 application

created by Viggo Navarsete in EJB3 - View the full discussion

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;

}

}

Reply to this message by going to Community

Start a new discussion in EJB3 at Community