habiba kessraoui
habiba kessraoui

Reputation: 13

J2EE - multiple database connections for different databases in JPA

I have an application which uses many databases in different geographical locations. All the databases contains same tables and only the database name is different according to the location. I have to create some statistic and monitoring charts in my application which uses data from each database.

What would be the proper way to create those database connection from a WEB java application with JSF and JPA.

Upvotes: 0

Views: 831

Answers (1)

Milkmaid
Milkmaid

Reputation: 1754

You can define more persistence units in your persistence.xml file:

<persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value=""/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value="/>
</properties>
</persistence-unit>

<persistence-unit name="pu2" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value=""/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value="/>
</properties>
</persistence-unit>

Now it depend if you are using full application server like TomEE or container (Tomcat).

@PersistenceContext(unitName = "pu1")
private EntityManager em;

@PersistenceContext(unitName = "pu2")
private EntityManager em2;

Otherwise:

 Persistence.createEntityManagerFactory("pu1");
 Persistence.createEntityManagerFactory("pu2");

Upvotes: 2

Related Questions