Viggo Navarsete [
http://community.jboss.org/people/viggo.navarsete] created the
discussion
"Re: Dinamically switch DataSource in EJB3 application"
To view the discussion, visit:
http://community.jboss.org/message/574235#574235
--------------------------------------------------------------
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
[
http://community.jboss.org/message/574235#574235]
Start a new discussion in EJB3 at Community
[
http://community.jboss.org/choose-container!input.jspa?contentType=1&...]