AdSense

網頁

2018/6/13

Hibernate JPA 設定多個資料庫來源

Hibernate JPA若要設定多個資料庫來源,則可在persistence.xml中設定多個persistence unit。

例如有兩個資料庫mydb1及mydb2,則persistence.xml設定如下。

persistence.xml

<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="mydb1" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>idv.matt.entity.Employee</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydb1?useSSL=false&characterEncoding=utf-8" />
            <property name="javax.persistence.jdbc.user" value="matt" />
            <property name="javax.persistence.jdbc.password" value="12345" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="none" />
        </properties>
    </persistence-unit>

    <persistence-unit name="mydb2" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>idv.matt.entity.Operator</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydb2?useSSL=false&characterEncoding=utf-8" />
            <property name="javax.persistence.jdbc.user" value="matt" />
            <property name="javax.persistence.jdbc.password" value="12345" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="none" />
        </properties>
    </persistence-unit>

</persistence>

使用<persistence-unit>定義的name在程式中取得要存取資料庫的EntityManagerFactory

EntityManagerFactory emf = Persistence.createEntityManagerFactory("mydb1");  

如果上面設定正確,卻出現No Persistence provider for EntityManager named [persistence-unit name]錯誤,可以試看看refresh一下專案中的persistence.xml檔。


參考:

沒有留言:

AdSense