Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use multiple databases with JPA?

Tags:

java

jpa

I need two or more than two connections in my web application using jpa

like image 361
Rahul Singh Avatar asked Feb 08 '23 18:02

Rahul Singh


1 Answers

To use different data sources, add multiple persistence units (say, source-1 and source-2 in persistence.xml and create multiple EntityManagerFactoryes by name):

EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("source-1");
EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("source-2");

or, if you're working on Spring or Java EE application server, inject them by name also:

@PersistenceUnit(name = "source-1")
EntityManagerFactory emf1;

@PersistenceContext(unitName = "source-2") // as an option
EntityManager em2;

persistence.xml will thus look like the following:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

    <persistence-unit name="source-1" transaction-type="RESOURCE_LOCAL">
        <properties>
            <!-- source-1 properties here -->
        </properties>
    </persistence-unit>

    <persistence-unit name="source-2" transaction-type="RESOURCE_LOCAL">
        <properties>
            <!-- source-2 properties here -->
        </properties>
    </persistence-unit>
</persistence>

Example of how to configure persistence unit, create EntityManager to manage entities and execute queries can be found here.

like image 102
Alex Salauyou Avatar answered Feb 11 '23 09:02

Alex Salauyou