2013-02-07 28 views
0

我有一個使用JPA提供的Hibernate和Tomcat的Web應用程序。我沒有DI框架,沒有Spring,沒有Guice,沒有完整的Java EE應用服務器。JPA(休眠)+ Tomcat +兩個不同的數據庫

我需要JPA連接到兩個不同的數據庫。我連接到的第一個數據庫是這樣的:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("mydb"); 
[...] 
EntityManager em = emf.createEntityManager(); 

,我必須在persistence.xml中聲明,並通過JNDI鏈接到context.xml中宣佈其資源的「mydb的」持久性單元。直到這裏永恆的作品。

現在我需要連接到另一個數據庫。我已經將它添加到persistence.xml和context.xml中,並將持久性單元命名爲「mydb2」。現在,我想我可以用這樣的:

EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("mydb2"); 
EntityManager em2 = emf2.createEntityManager(); 

Hibernate的配置,以驗證類和表上的兩個數據庫與

<property name="hibernate.archive.autodetection" value="class, hbm"/> 
<property name="hibernate.hbm2ddl.auto" value="validate"/> 
persistence.xml中

。然而,當我運行/調試webapp時,Hibernate會嘗試驗證屬於mydb上mydb的@Entity類,它顯然會失敗。現在有趣的部分是,如果我將Hibernate驗證屬性設置爲「無」,我的應用程序確實工作正常,並根據需要連接到正確的分貝...

有沒有辦法讓Hibernate只驗證類/屬於它們各自數據庫的表?

編輯:儘管可以在@Table註釋中指定目錄名稱,但在我的情況下,這不是一個好的解決方案,因爲我在生產中有多個此webapp實例,並且每個實例都連接到不同的數據庫對。在投入生產之前被迫觸摸源代碼是不好的。

回答

0

如果使用@ javax.persistence.Table註釋,則可以使用catalog參數來區分數據庫。編輯:嘗試定義單獨的hibernate-cfg.xml文件(將它們稱爲db1-hibernate-cfg.xml和db2-hibernate-cfg.xml),並在xml元素中使用該元素列出對應於那個工廠。你也可以在與JPA相對應的orm.xml中定義它們。

然後在Spring配置明確定義其休眠-CFG(或orm.xml中)映射到的EntityManager:使用Spring的LocalContainerEntityManagerFactoryBean

例子:

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
    <property name="persistenceUnitManager" ref="pum" /> 
    <property name="persistenceUnitName" value="my-pu" /> 
    <property name="jpaProperties"> 
     <props> 
      <prop key="hibernate.ejb.cfgfile">my-hibernate.cfg.xml</prop> 
          ... other configurations 
        </props> 
</bean> 

如果你去定義單獨的路徑orm.xml文件,然後在您的persistence-unit-manager中,爲每個實體管理器工廠(比如db1-persistence.xml和db2 ..)定義一個單獨的persistence.xml文件。 在persistence.xml文件中,使用元素來定義相應的orm.xml文件。

這些文件的默認位置是classpath-relative。

+0

這種方式我有硬編碼的目錄名稱,但我需要在部署之前更改它,因爲我在生產中有多個webapp實例,每個實例連接到不同的數據庫對(我要編輯我的問題來添加這個細節)。這當然是可能的,但我認爲不是一個好的解決方案。 –

+0

你有兩個diffeerebt hibernate.cfg.xml文件嗎? –

+0

我沒有,我只有一個存在。xml和一個context.xml。 –