Java 测试中没有EntityManager的持久性提供程序

Java 测试中没有EntityManager的持久性提供程序,java,hibernate,jpa,jakarta-ee,persistence,Java,Hibernate,Jpa,Jakarta Ee,Persistence,我是JavaEE新手,现在正在读“Goncalves A.开始JavaEE 7”这本书。我在为实体编写单元测试时遇到了一个问题。 我使用的是NetBeans 8.2、Hibernate 4.3和PostgreSQL 10.2 该项目是由带有JSF和Hibernate libs的新项目->Java Web->Web应用程序创建的 这是我的密码: Book.java @Entity public class Book implements Serializable { private st

我是JavaEE新手,现在正在读“Goncalves A.开始JavaEE 7”这本书。我在为实体编写单元测试时遇到了一个问题。 我使用的是NetBeans 8.2、Hibernate 4.3和PostgreSQL 10.2

该项目是由带有JSF和Hibernate libs的新项目->Java Web->Web应用程序创建的

这是我的密码:

Book.java

@Entity
public class Book implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @NotNull
    private String title;
    private Integer price;

    public Book(String title, Integer price) {
        this.title = title;
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }



    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Book)) {
            return false;
        }
        Book other = (Book) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "epic.Book[ id=" + id + " ]";
    }

}
public class BookTest {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("EpicWebAppTestPU");
    private EntityManager em;
    private EntityTransaction tx;

    @Before
    public void initEntityManager() throws Exception {
        em = emf.createEntityManager();
        tx = em.getTransaction();
    }

    @After
    public void closeEntityManager() throws Exception {
        if (em != null) {
            em.close();
        }
    }

    @Test
    public void shouldCreateBook() throws Exception {

        Book book = new Book("EpicBook", 9999);

        tx.begin();
        em.persist(book);
        tx.commit();
        Assert.assertNotNull( book.getId());
    }
}
BookTest.java

@Entity
public class Book implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @NotNull
    private String title;
    private Integer price;

    public Book(String title, Integer price) {
        this.title = title;
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }



    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Book)) {
            return false;
        }
        Book other = (Book) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "epic.Book[ id=" + id + " ]";
    }

}
public class BookTest {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("EpicWebAppTestPU");
    private EntityManager em;
    private EntityTransaction tx;

    @Before
    public void initEntityManager() throws Exception {
        em = emf.createEntityManager();
        tx = em.getTransaction();
    }

    @After
    public void closeEntityManager() throws Exception {
        if (em != null) {
            em.close();
        }
    }

    @Test
    public void shouldCreateBook() throws Exception {

        Book book = new Book("EpicBook", 9999);

        tx.begin();
        em.persist(book);
        tx.commit();
        Assert.assertNotNull( book.getId());
    }
}
\src\conf\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="EpicWebAppPU" transaction-type="JTA">
  <provider>org.hibernate.ejb.HibernatePersistence</provider>        


    <class>com.epic.Book</class>
    <properties>
        <property name="javax.persistence.schema-generation-action" value="drop-and-create"/>
        <property name="javax.persistence.schema-generation-target" value="database"/>
        <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/cosuket;create=true"/>
                <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value="toor"/>
    </properties>
  </persistence-unit>

  <persistence-unit name="EpicWebAppTestPU" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.epic.Book</class>
    <properties>
        <property name="javax.persistence.schema-generation-action" value="drop-and-create"/>
        <property name="javax.persistence.schema-generation-target" value="database"/>
        <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/cosuketTest;create=true"/>
                <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value="toor"/>
    </properties>
</persistence-unit>

</persistence>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.epic</groupId>
    <artifactId>EpicWebMaven</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>EpicWebMaven</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        <dependency>
            <groupId>unknown.binary</groupId>
            <artifactId>hibernate-jpamodelgen-4.3.1.Final</artifactId>
            <version>SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.2.jre7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>unknown-jars-temp-repo</id>
            <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
            <url>file:${project.basedir}/lib</url>
        </repository>
    </repositories>
</project>
org.hibernate.ejb.HibernatePersistence应该可以工作

尝试使用以下提供程序:

org.hibernate.jpa.HibernatePersistenceProvider

如果仍然无法工作,则可能缺少一个罐子


检查hibernate entitymanager jar是否存在。

您使用的是maven吗?如果是,请添加pom.xml。如果没有,请在项目中添加jar依赖项列表。非常感谢。问题在于缺少测试范围的hibernate库。所以我决定和maven一起重建这个项目。它现在可以找到持久性单元,但我有另一个错误:em=emf.createEntityManager()的NullPointerException;。查看我的更新。这可能会有帮助。您是否尝试将提供程序更改为org.hibernate.jpa.HibernatePersistenceProvider?是的,我尝试过,但没有看到差异。现在它终于起作用了。这个链接真的很有帮助。NullPointerException的解决方案是