如何在JPA中使用多个数据库?

时间:2015-10-21 10:58:27

标签: java jpa

我使用jpa

在我的网络应用程序中需要两个或两个以上的连接

2 个答案:

答案 0 :(得分:6)

要使用不同的数据源,请在source-1中添加多个持久性单位(例如source-2persistence.xml,并按名称创建多个EntityManagerFactory):

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

答案 1 :(得分:-3)

对于单个数据源,jpa将在内部使用多个连接。因此您无需执行任何操作。

相关问题