I need two or more than two connections in my web application using jpa
Asked
Active
Viewed 1.1k times
4
-
are you talking about multiple data sources? Because DB connections and data sources are quite different terms. – Ish Oct 21 '15 at 11:09
-
two data sources like both will be a oracle database but the crdentials sid and all will be different for the two data sources – Rahul Singh Oct 21 '15 at 11:12
2 Answers
12
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.

Alex Salauyou
- 14,185
- 5
- 45
- 67
-
1Can you please share a example of such as i m new to this concept and not able to decide what to do – Rahul Singh Oct 21 '15 at 11:15
-
it is telling muliplt persistence unit defined only the first persistence unit will be identified – Rahul Singh Oct 21 '15 at 11:20
-
@RahulSingh Hibernate will define all persistence units listed in `persistence.xml`, tested many times. Please see this post: http://stackoverflow.com/questions/5356152/two-persistence-unit-in-one-persistence-xml – Alex Salauyou Oct 21 '15 at 11:25
-5
For single datasource jpa will use multiple connections internally.So you don't need to do anything.

Sainik Kumar Singhal
- 811
- 6
- 7
-
The question is not about connections to the same database,but to multiple different DBs. Though, I understand that the wording in the question is confusing – OndroMih Oct 22 '15 at 16:23