【发布时间】:2015-10-21 10:58:26
【问题描述】:
我需要在我的网络应用程序中使用 jpa 进行两个或两个以上的连接
【问题讨论】:
-
你说的是多数据源吗?因为数据库连接和数据源是完全不同的术语。
-
两个数据源都将是一个 oracle 数据库,但两个数据源的凭证 sid 和 all 将不同
我需要在我的网络应用程序中使用 jpa 进行两个或两个以上的连接
【问题讨论】:
要使用不同的数据源,请添加多个持久性单元(例如,persistence.xml 中的 source-1 和 source-2 并按名称创建多个 EntityManagerFactoryes):
EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("source-1");
EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("source-2");
或者,如果您正在使用 Spring 或 Java EE 应用程序服务器,也可以按名称注入它们:
@PersistenceUnit(name = "source-1")
EntityManagerFactory emf1;
@PersistenceContext(unitName = "source-2") // as an option
EntityManager em2;
persistence.xml 将如下所示:
<?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>
关于如何配置持久化单元、创建EntityManager来管理实体和执行查询的例子可以在here找到。
【讨论】:
persistence.xml 中列出的所有持久性单元,并经过多次测试。请看这个帖子:stackoverflow.com/questions/5356152/…
对于单个数据源,jpa 将在内部使用多个连接。因此您无需执行任何操作。
【讨论】: