gpt4 book ai didi

java - 没有名为 X 的 EntityManager 的持久性提供程序

转载 作者:搜寻专家 更新时间:2023-10-30 19:51:59 26 4
gpt4 key购买 nike

我正在使用 JPA 开发 JavaSE 应用程序。不幸的是,我在调用后得到了 null:Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

下面你会发现:

  • 调用 EntityManagerFactory 并意外返回 null 的代码片段
  • 我的persistence.xml 文件
  • 我的项目结构

我的代码片段:

public class Main {
private static final String PERSISTENCE_UNIT_NAME = "MeineJpaPU";
private static EntityManagerFactory factory;

public static void main(String[] args) {
// I get null on this line!!!
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

EntityManager em = factory.createEntityManager();
// do stuff with entity manager
...
}
}

我的 persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="MeineJpaPU" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>path.to.package.server.Todo</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/test"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="postgres"/>
</properties>
</persistence-unit>
</persistence>

我的项目结构:

This is the structure of my project:

最佳答案

您必须将 persistence.xml 文件移动到适当的位置。

更具体地说,将 META-INF/persistence.xml 文件添加到源文件夹的根目录。

在这种情况下,以下是合适的位置:src\main\java\META-INF\persistence.xml

详情如下:(取自JPA 规范)

A persistence.xml file defines a persistence unit. The persistence.xml file is located in the META-INF directory of the root of the persistence unit.

持久化单元的根是这里的关键。

如果您是非 Java EE 应用

The jar file or directory whose META-INF directory contains the persistence.xml file is termed the root of the persistence unit.

如果您使用的是 Java EE 应用,则以下内容有效

In Java EE environments, the root of a persistence unit must be one of the following:

  • an EJB-JAR file
  • the WEB-INF/classes directory of a WAR file[80]
  • a jar file in the WEB-INF/lib directory of a WAR file
  • a jar file in the EAR library directory
  • an application client jar file

关于java - 没有名为 X 的 EntityManager 的持久性提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19322827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com