如何在JPA中使用多个数据库? [英] How do I use multiple databases with JPA?

查看:309
本文介绍了如何在JPA中使用多个数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need two or more than two connections in my web application using jpa

推荐答案

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

To use different data sources, add multiple persistence units (say, source-1 and source-2 in persistence.xml and create multiple EntityManagerFactoryes by name):

EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("source-1");
EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("source-2");

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

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因此将如下所示:

<?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以管理实体并执行查询的示例,请参见

Example of how to configure persistence unit, create EntityManager to manage entities and execute queries can be found here.

这篇关于如何在JPA中使用多个数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆