How to use multiple database in persistence.xml?

The Java Persistence API allows you to define multiple persistence units, each of which can map to a separate database.

In order to use multiple Database, simply define a persistent-unit for each one in the persistence.xml file :

  <persistence>
    <persistence-unit name="sample-db1">
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
     <jta-data-source>jdbc/SamplesDB</jta-data-source>
    </persistence-unit>
    <persistence-unit name="sample-db2">
     <provider>
      oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
     </provider>
     <jta-data-source>jdbc/SamplesDB2</jta-data-source>
    </persistence-unit>
   </persistence>

In te above example, the sample-db1 and sample-db2 persistence units have been configured in the persistence.xml file.

You can use @PersistenceContext attribute unitName to specify which persistent unit to use in your code:

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {

    @PersistenceContext(unitName="sample-db1") 
    protected EntityManager em1;

    @PersistenceContext(unitName="sample-db2") 
    protected EntityManager em2;

    public void createEmployee(String fName, String lName) {
        Employee employee  = new Employee();
        employee.setFirstName(fName);
        employee.setLastName(lName);
        em1.persist(employee);
    }
...
}
Found the article helpful? if so please follow us on Socials