2017-03-01 68 views
0

我正在用JPA模式開發具有Hibernate的純Java應用程序。 persistence.xml文件中包含了一個持久化單元,其中:如何在persistence.xml中支持多種配置?

  • 使用類標籤
  • 定義了其他選項,如架構的每一個上自動創建包含訪問憑據的數據庫
  • 列出了所有使用的entites應用程序的開始

現在我們正在發佈應用程序,並且我想要配置:測試模式,開發模式和生產模式。他們顯然會擁有不同的數據庫訪問憑據和自動更新選項。

我能想到的只有缺點我唯一的可能性:

  1. 有多個persistence.xml中?糟糕的想法,因爲實體類是在持久性單元內聲明的。我將不得不將它們維護在三個persistence.xml文件中
  2. 在一個persistence.xml中有多個持久單元嗎?也不好的想法,因爲我不得不復制所有實體類標籤到他們每個人。

我該怎麼做?

回答

0

我能想到的一個解決方案是,如果您有一種檢測應用程序環境的方法,則可以使用不同的屬性啓動它。 而不是調用的:

Persistence.createEntityManagerFactory("our.unit"); 

使用

Map<String, Object> props = new TreeMap<>(); 
Persistence.createEntityManagerFactory("our.unit",props); 

,其中屬性會根據環境來填補。

這當然,除非你使用CDI。

+0

聽起來不錯。我不知道你可以傳遞第二個參數。我會嘗試。謝謝! – Wombat

+0

@Wombat有沒有運氣? – coladict

+0

您的解決方案正在運行,我正在使用它作爲當前的解決方案。但它有一些薄弱點:傳入「hibernate.hbm2ddl.auto」不起作用(因爲它不是JPA標準參數)。如果我們將這個參數保存在「單個」persistence.xml文件中,那麼我們有可能會忘記將其關閉,並且生產數據庫將被清除。所以我寧願有多個持久性。xml但不起作用,因爲我必須在那裏列出所有實體,否則它們將不會被EntityManagerFactory找到。 – Wombat

0

爲什麼你需要將所有標籤複製到它們中的每一個,如果你將兩個持久性單元使用相同的實體?

,爲什麼你就是不使用

<exclude-unlisted-classes>false</exclude-unlisted-classes>

例如:

<persistence 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" 
    version="2.1"> 

    <persistence-unit name="persistenceUnit_1"> 
     <provider> xxx </provider> 
     <jta-data-source> xxxx </jta-data-source> 
     <exclude-unlisted-classes>false</exclude-unlisted-classes> 
     <properties> 
      //Properties of first persistence unit 
     </properties> 
    </persistence-unit> 

    <persistence-unit name="persistenceUnit_2"> 
     <provider> xxx </provider> 
     <jta-data-source> xxxx </jta-data-source> 
     <exclude-unlisted-classes>false</exclude-unlisted-classes> 
     <properties> 
      //Properties of second persistence unit 
     </properties> 
    </persistence-unit> 

</persistence> 

在這種情況下,你需要通過名字來使用它,例如

@PersistenceContext(unitName = "persistenceUnit_1") 
private EntityManager entityManager; 
+0

如果我沒有列出persistence.xml中的所有類,Hibernate會告訴我這些實體沒有被映射。所有實體都位於包含源的不同項目中。不幸的是,您的解決方案對我無效。 – Wombat

+1

'exclude-unlisted-classes'只在實體處於與persistence.xml相同的類路徑級別時才起作用。另一個解決方案是,如果你可以在他們自己的'jar'中分開它們,並且把' myentities.jar'添加到你的'persistence.xml'中。這迫使Hibernate在整個應用程序範圍內查找文件,就像單獨列出類一樣。 – coladict