将提供`EntityManagerFactory`解决`无法检索unitName xyz`

时间:2016-09-25 19:57:44

标签: java mysql hibernate java-ee entitymanager

这是堆栈跟踪的(底部)错误:

Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:171)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createQuery(EntityManagerWrapper.java:477)
...

代码如下(受我今天在SO上发现的@BalusC示例的启发):

@Stateless
public class GradService {

    @PersistenceContext
    private EntityManager em;

    public List<Grad> listAll() {
        return em.createQuery("SELECT g FROM Grad g", Grad.class).getResultList();
    }
}

作为参考,这是我的persistence.xml(webmodule-root:配置文件: WEB-INF META-INF:persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 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">
    <persistence-unit name="MojaPU" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>jdbc/ekstraResource</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

1 个答案:

答案 0 :(得分:1)

看来,您将persistence.xml文件放在了错误的位置。它应该位于/ META-INF /文件夹中而不是WEB-INF中。