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);
}
...
}
Recommended Articles
Configure WildFly 11 for JMS JDBC Persistence Store using MySQL - Step-by-Step Guide
Learn how to set up a WildFly 11 server with JMS JDBC Store persistence using MySQL. Follow this tutorial to configure WildFly, create a datasource, and deploy a JMS quickstart.
Optimized Database Connection Management in Java: Using Try-With-Resources
Learn how to manage database connections efficiently using Java's try-with-resources feature for cleaner, safer code.
Configure WildFly 11 Elytron JDBC Realm with MySQL Database - Step-by-Step Guide
Learn how to configure an Elytron JDBC Realm on WildFly 11 using both Web Console and CLI. Prerequisites: MySQL Database, WildFly 11 or newer.
Troubleshooting WildFly DataSource Connection Leaks and Pool Management
Fixing connection leaks and optimizing WildFly DataSource pool size for seamless database access. #Java #WildFly #DatabaseConnection