2015-10-21 15 views
3

我需要兩個或兩個以上的連接在我的web應用程序中使用jpa如何在JPA中使用多個數據庫?

+0

你是在談論多個數據源?因爲數據庫連接和數據源是完全不同的術語。 – Ish

+0

兩個數據源都是oracle數據庫,但是對於兩個數據源,crdentials sid和所有數據源都不相同 –

回答

-1

對於單數據源jpa將在內部使用多個連接。因此,您不需要執行任何操作。

+0

問題不在於連接到同一個數據庫,而是連接到多個不同的數據庫。雖然,我知道這個問題的措辭令人困惑 – OndrejM

5

要使用不同的數據源,(通過名字說,source-1source-2persistence.xml和創建多個EntityManagerFactory ES)添加多個持久化單元:

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

或者,如果你在春天或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

+0

可以請你分享一個例子,比如說這個概念是新的,而不能決定做什麼 –

+0

它告訴多重持久單元定義只有第一個持久單元將是確定 –

+0

@RahulSingh Hibernate將定義'persistence.xml'中列出的所有持久性單元,經過多次測試。請參閱此帖:http://stackoverflow.com/questions/5356152/two-persistence-unit-in-one-persistence-xml –

相關問題