2014-01-09 31 views

回答

1

還有另一種更簡單的可能性,讓您的數據源名稱和其他應用程序參數可配置。

我們使用maven配置文件和資源過濾。您需要在您的persistence.xml中定義與您的.properties文件中的屬性名稱相匹配的佔位符或.pom

在構建過程中,您指定了配置文件,maven將用您的屬性替換佔位符。

我們已經使用這種技術在不同的部署環境之間切換數據源。

編輯:

首先,定義資源篩選配置文件:

<profiles> 
    <profile> 
    <id>set_datasource</id> 
    <build> 
     <!-- enable resource filter to set the datasource name -- 
     <resources> 
      <resource> 
      <directory>src/main/resources</directory> 
      <filtering>true</filtering> 
     ... 

爲每個數據源配置文件:

<profile> 
     <id>db_test</id> 
    <properties> 
     <database.name>test_ds</database.name> 
    </properties> 
</profile> 

在您的持久性單元,準備佔位符

<persistence-unit name="my_db"> 
    <jta-data-source>java:jboss/datasources/${datasource.name}</jta-data-source> 
    </persistence-unit> 

與這兩個配置文件呼叫maven:

mvn test -Pdatasource,db_test 
+0

可以請你添加一些示例代碼,它會有很大的幫助。 –

+0

@Sai請參閱編輯,希望它有幫助。 – kostja

1

通過使用Persistence.createEntityManagerFactory(persistenceUnitName, properties)動態生成EntityManagerFactory,並使用properties映射來指定數據源名稱,可以覆蓋persistence.xml文件中的值。但是,現在您永遠不可以在您的應用程序的任何位置使用@PersistenceContext注入EntityManager或使用@PersistenceUnit注入EntityManagerFactory,並且您必須手動管理您的EntityManager事務。不要這樣做。這是一個可怕的想法。

+1

感謝里恩它會幫助。 –

相關問題