我一直在尝试使用 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 文件?