如何在persistence.xml中添加多个持久性单元?

时间:2013-05-16 22:12:47

标签: java-ee jpa

这是正确的用法吗?

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="UserBean">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.tugay.registiration.UserBean</class>
        <properties>
            <property name="javax.persistence.jdbc.driver"
                      value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url"
                      value="jdbc:mysql://localhost:3306/sampleapplication"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="****"/>
        </properties>
    </persistence-unit>

    <persistence-unit name="CustomerBean">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.tugay.registiration.CustomerBean</class>
        <properties>
            <property name="javax.persistence.jdbc.driver"
                      value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url"
                      value="jdbc:mysql://localhost:3306/sampleapplication"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="****"/>
        </properties>
    </persistence-unit>

</persistence>

1 个答案:

答案 0 :(得分:0)

无论如何,既然你正在写同一个数据库,为什么还要麻烦,不要简单地将所有类都添加到一个数据库中?

但如果这是你需要的。如果要在同一文件中包含两个单元,请在类标记后添加<exclude-unlisted-classes>true</exclude-unlisted-classes>以排除那些不属于此持久性单元的单元。否则持久性A可以插入持久性B的实例。

在我看来,你最好有两个独立的persistence.xml。在不同的文件夹中或使用不同的名称。

请记住,您需要两个单独的EntityManagerscontexts

<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="UserBean">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.tugay.registiration.UserBean</class>
        <class>com.tugay.registiration.CustomerBean</class>
        <properties>
            <property name="javax.persistence.jdbc.driver"
                  value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url"
                  value="jdbc:mysql://localhost:3306/sampleapplication"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="****"/>
        </properties>
    </persistence-unit>
 </persistence>