Hibernate Error “No Persistence Provider for EntityManager” – Hibernate Error “No Persistence Provider for EntityManager”

最后修改: 2020年 4月 17日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we’ll see how to solve a common Hibernate error — “No persistence provider for EntityManager”. Simply put, persistence provider refers to the specific JPA implementation used in our application to persist objects to the database.

在本教程中,我们将看到如何解决一个常见的Hibernate错误 – “No persistence provider for EntityManager” 。简单地说,持久化提供者指的是我们的应用程序中用于将对象持久化到数据库的特定JPA实现。

To learn more about JPA and its implementations, we can refer to our article on the difference between JPA, Hibernate, and EclipseLink.

要了解更多关于JPA及其实现的信息,我们可以参考我们关于JPA、Hibernate和EclipseLink之间的区别的文章

2. What Causes the Error

2.导致错误的原因

We’ll see the error when the application doesn’t know which persistence provider should be used.

应用程序不知道应该使用哪个持久性提供者时,我们会看到错误。

This occurs when the persistence provider is neither mentioned in the persistence.xml file nor configured in the PersistenceUnitInfo implementation class.

当持久化提供者既没有在persistence.xml文件中提到,也没有在PersistenceUnitInfo实现类中配置时,就会发生这种情况。

3. Fixing the Error

3.纠正错误

To fix this error, we simply need to define the persistence provider in the persistence.xml file:

为了解决这个错误,我们只需要persistence.xml文件中定义持久性提供者。

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

Or, if we’re using Hibernate version 4.2 or older:

或者,如果我们使用Hibernate 4.2或更早的版本

<provider>org.hibernate.ejb.HibernatePersistence</provider>

In case we’ve implemented the PersistenceUnitInfo interface in our application, we must also override the
getPersistenceProviderClassName() method:

如果我们已经在我们的应用程序中实现了PersistenceUnitInfo接口,我们也必须覆盖
getPersistenceProviderClassName()方法。

@Override
public String getPersistenceProviderClassName() {
    return HibernatePersistenceProvider.class.getName();
}

To ensure all the necessary Hibernate jars are available, it’s important to add the hibernate-core dependency in the pom.xml file:

为了确保所有必要的Hibernate罐子都可用,在pom.xml文件中添加hibernate-core依赖是很重要的。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>${hibernate.version}</version>
</dependency>

4. Conclusion

4.总结

To summarize, we’ve seen the possible causes of the Hibernate error “No persistence provider for EntityManager” and various ways to solve it.

总结一下,我们已经看到了造成Hibernate错误 “No persistence provider for EntityManager “的可能原因以及解决它的各种方法。

As usual, the sample Hibernate project is available over on GitHub.

像往常一样,Hibernate项目的样本可以在GitHub上找到