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 factory.
here is where you apply the solution that Michael and Milosz were taking about.
eg:
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.
<pre>
String dsName = String.format("%1$sDb", clientCode);
Resource res = new Resource(dsName, "javax.sql.DataSource");
res.setJndi(dsName);
Properties props = res.getProperties();
props.put("JdbcDriver", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
props.put("JdbcUrl", String.format("jdbc:sqlserver://172.19.101.12;databaseName=%1$s_db", clientCode));
props.put("UserName", "sa");
props.put("Password", "whatever");
props.put("JtaManaged", "true");
try
{
Assembler component = SystemInstance.get().getComponent(Assembler.class);
component.createResource(new ConfigurationFactory().configureService(res, ResourceInfo.class));
Thread.yield();
}
catch (OpenEJBException e)
{
throw e;
}
</pre>
Hope that it helps
Daryl Stultz wrote:
On Sat, Nov 7, 2009 at 7:53 PM, rtselvan <rtselvan@gmail.com> 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.
http://www.6degrees.commailto:daryl@6degrees.com