eclipse - 使用 Eclipse 的 Postgres 的基本独立 JPA 示例

标签 eclipse postgresql jpa

我一直在尝试获得一个非常基本的独立 JPA 示例,以使用 Eclipse IDE 与 Postgres 一起工作。

我定义了一个 persistance.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="sample" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>package.class</class>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="eclipselink.logging.level" value="INFO" />
            <property name="eclipselink.jdbc.driver" value="org.postgresql.Driver" />
            <property name="eclipselink.jdbc.url"
                value="jdbc:postgresql://localhost:5432/sample" />
            <property name="eclipselink.jdbc.user" value="scott" />
            <property name="eclipselink.jdbc.password" value="tiger" />
        </properties>
    </persistence-unit>
</persistence>

此文件位于 src/main/resources/META-INF 文件夹中。我已将 src/main/resources 文件夹包含到我的 eclipse 源目录中。我定义了一个名为 User 的简单实体。当我尝试创建该实体时

EntityManagerFactory entityManagerFactory 
         = Persistence.createEntityManagerFactory("sample");
     EntityManager em = entityManagerFactory.createEntityManager();
     EntityTransaction tx = em.getTransaction();
     try {
         User user = new User();
         user.setEnabled(false);
         user.setEmailId("test@test.com");
         tx.begin();
          em.persist(user);
         tx.commit();
     } catch (Exception e) {
         em.getTransaction().rollback();
     } finally {
         em.close();
     }

我得到以下异常 - Exception in thread "main"javax.persistence.PersistenceException: No Persistence provider for EntityManager named sample

我的 persistance.xml 文件似乎没有被提取。 JPA 框架在哪里寻找加载 persistance.xml 文件?

最佳答案

这是一个愚蠢的错误。该文件需要调用 persistence.xml 而不是 persistance.xml。

关于eclipse - 使用 Eclipse 的 Postgres 的基本独立 JPA 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14611052/

相关文章:

java - 在Eclipse中构建Maven项目时出现错误,退出命令提示符后还检查maven版本

postgresql - postgresql嵌套异常可能吗?

CentOS 6.5 上的 PHP 无法连接到 Postgres DB

java - 使用 Spring+JPA 的单元测试 Service bean,但没有可用的 DB

rest - 错误: Getters of lazy classes cannot be final Kotlin Spring Boot

java - entity.merge后如何获取主键

java - 如何在 Eclipse 加载时激活插件?

java - 将动态 Web 项目转换为 JPA 项目?

android - 如何在每个 Android Activity 中添加图像按钮?

java - Postgres 和 GWT 的主要提供商