2012-11-14 30 views
0

我有一個應用程序使用一個數據庫,現在我有這個數據訪問配置文件配置。需要連接兩個數據庫Hibernate和JPA

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> 
    <!-- Instructs Spring to perfrom declarative transaction management on annotated classes --> 
    <tx:annotation-driven /> 
    <!-- Drives transactions using local JPA APIs --> 
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
     <property name="entityManagerFactory" ref="entityManagerFactory" /> 
    </bean> 
    <!-- Creates a EntityManagerFactory for use with the Hibernate JPA provider and a simple in-memory data source populated with test data --> 
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="jpaVendorAdapter"> 
      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> 
     </property> 
    </bean> 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="org.postgresql.Driver" /> 
     <property name="url" value="jdbc:postgresql://localhost:5432/database1" /> 
     <property name="username" value="admin1" /> 
     <property name="password" value="some_pass" /> 
    </bean> 
</beans> 

它連接好,但現在我需要配置第二個數據庫(在同一臺服務器),試圖複製的EntityManagerFactory但拋出一個錯誤,即不能有兩個實體的經理在同一時間,以便即時通訊困惑這裏。我使用休眠+ JPA +彈簧

謝謝!

回答

1

像這樣的東西應該工作,我相信:

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
    <property name="dataSource" ref="dataSource" /> 
    ... 
</bean> 

<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
    <property name="dataSource" ref="dataSource1" /> 
    ... 
</bean> 

中DAO,使用

@PersistenceContext(unitName = "emf1") 
private EntityManager em; 

上面會告訴DAO使用emf1實例。

也許你忘了你的名字第二個實體管理器的東西比你的第一個有什麼不同?

+0

沒有我改名爲第二個實體。這是我從系統得到的消息:org.springframework.beans.factory.NoSuchBeanDefinitionException:致型[javax.persistence.EntityManagerFactory]定義的無獨特豆:預計一個bean,但發現2 – user1352643

+0

您使用的註解? –

+0

您可能得到的可能是Spring會嘗試通過它的類型來獲得一個bean,除非您專門說明了它的名稱。所以它正在尋找一個'EntityManagerFactor'對象,但找到2.因此它不知道要使用哪個對象。如果您使用註釋,則需要添加名稱。 –

0

您可能需要使用到「持久化部門經理」,這將幫助您管理持久化單元。請參閱Spring documentation on multiple persistence units。您將擁有2個數據源,1個實體管理器工廠和1個持久性單元管理器。

實體管理因子必須將持久性單元管理器(而不是2個的數據源)的引用,那麼持久單元管理器必須將2個數據源的參考。

+0

在EMF中對PU做一個引用。像如果我在persistence.xml中有兩個PU,我是否需要添加另一個?我對此的理解是春天自動把這兩個PU(獨立於數據庫引擎)。所以在DAO中,例如我們只參考一個PU(總是連接到定義的兩個DS)。是對的嗎? – user1352643