I need two or more than two connections in my web application using jpa
To use different data sources, add multiple persistence units (say, source-1
and source-2
in persistence.xml
and create multiple EntityManagerFactory
es 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.
For single datasource jpa will use multiple connections internally.So you don't need to do anything.