1. Introduction

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.

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

2. What Causes the Error

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.

3. Fixing the Error

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

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

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

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

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

@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:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>6.1.7.Final</version>
</dependency>

4. Conclusion

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

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