was下jpa配置多個資料來源 more datasource

來源:互聯網
上載者:User

jpa 下配置多個資料來源 ,可以依據jpa的規範,在persistence.xml 裡面配置多個<persistence-unit>,

 

當然,persistence-unit的名字不能重複:

 

<persistence-unit name="TODS"  transaction-type="JTA">
        <provider>
            org.apache.openjpa.persistence.PersistenceProviderImpl
        </provider>
        <jta-data-source>jdbc/TODS</jta-data-source>
        <class>com.ibm.its.itmc.entity.Zone</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
          <property name="openjpa.jdbc.Schema" value="TODS" />      
          <property name="openjpa.jdbc.DBDictionary" value="db2" />      
          <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
          <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
        </properties>
    </persistence-unit>
   
    <persistence-unit name="TADS" transaction-type="JTA">
        <provider>
            org.apache.openjpa.persistence.PersistenceProviderImpl
        </provider>
        <jta-data-source>jdbc/testVD</jta-data-source>
        <class>com.ibm.its.itmc.entity.TadsZone</class>
        <class>com.ibm.its.itmc.entity.TadsRoad</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>       
        <properties>
          <property name="openjpa.jdbc.Schema" value="db2admin" />      
          <property name="openjpa.jdbc.DBDictionary" value="db2" />      
          <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
          <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
        </properties>
    </persistence-unit>

 

當然也可以配置更多的資料來源,我這裡只配了兩個。

 

在調用的時候,只要指定不同的unit-name給jpa的EntityManager就可以了:

 

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

或者

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

 

然後通過em就可以訪問不同的資料來源下面的實體了。至於orm.xml不用修改,注意一定是unitName, 而不是name,

如果只是一個資料來源,寫name就能預設找到datasource , 但是多個資料來源不配置@PersistenceContext(unitName="TADS")

而唯寫@PersistenceContext(name="TADS"), 會報TODS can not resolve. 的錯誤。

 

這隻是在was下面使用jpa的經驗,希望能帶給你些提示。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.