我一直在尝试使用Eclipse IDE获得一个非常基本的独立JPA示例来使用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文件?
答案 0 :(得分:6)
这是一个愚蠢的错误。该文件需要调用persistence.xml而不是persistance.xml。