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:
Example of how to configure persistence unit, create EntityManager
to manage entities and execute queries can be found here.