如何在JavaEE应用程序的一个Persistence.xml中使用2个PersistenceUnits?

时间:2013-06-17 22:33:09

标签: jpa persistence persistence-unit

我正在尝试访问数据库中的两个不同的表。

最初我的persistence.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="Persistence">
        <jta-data-source>jdbc/classicmodels</jta-data-source>
        <class>com.tugay.maythirty.model.Customers</class>
        <class>com.tugay.maythirty.model.Products</class>
        <class>com.tugay.maythirty.model.Employee</class>
        <class>com.tugay.maythirty.model.Office</class>
    </persistence-unit>
</persistence>

所以我在Glassfish之后使用this很棒的艺术定义了一个DataSource,我的应用程序运行正常。我在我的DAO课程中使用 @PersistenceContext 注释 name =“Persistence”

这基本上连接到一个名为“classicmodels”的表。

然后我需要从名为“sakila”的表中获取一些数据。我将这些行添加到我的persistence.xml:

<persistence-unit name="sakila">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.tugay.maythirty.model.Actor</class>
    <class>com.tugay.maythirty.model.Film</class>
    <class>com.tugay.maythirty.model.FilmActor</class>
    <properties>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/sakila"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value="password"/>
    </properties>
</persistence-unit>

我在DAO中使用了这段代码:

public List<Actor> getAllActors(){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("sakila");
        EntityManager em = emf.createEntityManager();
        TypedQuery<Actor> actorTypedQuery = em.createQuery("Select a from Actor a",Actor.class);
        return actorTypedQuery.getResultList();
}

当我将我的应用程序部署到GlassFish时,我开始得到这个例外:

java.lang.RuntimeException: Could not resolve a persistence unit corresponding to the persistence-context-ref-name [Persistence] in the scope of the module called [may-thrity]. Please verify your application.

所以现在似乎我的持久性单位名称为“持久性”已经消失了。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用

明确声明持久性单元

@PersistenceContext(unitName="Persistence")

而不是

@PersistenceContext(name="Persistence")

PersistenceContext doc