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

Rah*_*ngh 4 java jpa

我使用jpa在我的Web应用程序中需要两个或两个以上的连接

Ale*_*you 8

要使用不同的数据源,(比如,添加多个持久化单元source-1,并source-2persistence.xml和创建多个EntityManagerFactory名字ES):

EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("source-1");
EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("source-2");
Run Code Online (Sandbox Code Playgroud)

或者,如果您正在使用Spring或Java EE应用程序服务器,请按名称注入它们:

@PersistenceUnit(name = "source-1")
EntityManagerFactory emf1;

@PersistenceContext(unitName = "source-2") // as an option
EntityManager em2;
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

EntityManager可在此处找到如何配置持久性单元,创建以管理实体和执行查询的示例.