openjpa-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rtselvan <>
Subject Re: overriding datasource in the persistent unit
Date Sun, 08 Nov 2009 04:41:47 GMT

Correct, you need to create a separate instance of the EntityManagerFactory
for each organization by passing in the datasource name. it means that you
create the factory.createEntityManager() for each thread based on the

here is where you apply the solution that Michael and Milosz were taking


		EntityManagerFactory emf = factories.get(client); 
		if (emf == null) 
			Map<String, String> props = new HashMap<String, String>();
			props.put("javax.persistence.jtaDataSource", "jdbc/" + client + "db");
			emf = Persistence.createEntityManagerFactory("pu", props);
			factories.put(client, emf);
		EntityManager em = emf.createEntityManager();

also, you need to create the data sources programmatically if you adding new
organizations while application is live.  If you are interested here is an
example of it.

		String dsName = String.format("%1$sDb", clientCode);
		Resource res = new Resource(dsName, "javax.sql.DataSource");
		Properties props = res.getProperties();
		props.put("JdbcDriver", "");
		props.put("UserName", "sa");
		props.put("Password", "whatever");
		props.put("JtaManaged", "true");
			Assembler component = SystemInstance.get().getComponent(Assembler.class);
			component.createResource(new ConfigurationFactory().configureService(res,
		catch (OpenEJBException e) 
			throw e;

Hope that it helps 

Daryl Stultz wrote:
> On Sat, Nov 7, 2009 at 7:53 PM, rtselvan <> wrote:
>> There may be some difference in what you are doing though. I have one
>> only
>> persistence unit in the XML file and connecting to different database
>> based
>> on the user/organization. This avoids to creating a lot of persistence
>> unit
>> and as well, ability to add additional organization without having change
>> the persistence unit xml file.
> Yeah, I definitely want to be able to add and drop organizations while the
> application is live, thus no changes to persistence.xml. But isn't a one
> to
> one correspondence between persistence unit and database implied? How does
> JPA know the difference between 2 entities of the same class with the same
> ID but from different databases?
> I'm using a DataSource to get connections from my connection pool, I can
> see
> clearly how I can choose a connection from different databases, but I
> would
> think JPA would get very confused if I did that.
> -- 
> Daryl Stultz
> _____________________________________
> 6 Degrees Software and Consulting, Inc.

View this message in context:
Sent from the OpenJPA Users mailing list archive at

View raw message