Skip to content
javahacks.dev
Hibernate

What Hibernate and JPA Are and How They Relate in Spring

JPA is a specification and Hibernate is the implementation most Java projects use. See how the two relate to Spring Data and JDBC in a running application.

6 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the Hibernate, Spring, Spring Boot, PostgreSQL and MySQL logos.

"Do we use Hibernate or JPA?" is a question that has no answer, because the two sit at different levels of the same stack. Asking it is like asking whether you use SQL or PostgreSQL. The confusion costs teams real time: an annotation imported from the wrong package, a dependency pinned to the wrong thing, a bug report filed against the wrong project, an interview answer that goes sideways. This post separates the layers, shows each in code, explains what a Spring Boot 4 project pulls in, and gives the practical rule for when the distinction changes what you write. Examples use Jakarta Persistence 3.2, Hibernate ORM 7 and Spring Data JPA 4.

Four layers, top to bottom

When your service saves an Order, the call passes through four distinct things.

LayerWhat it isWho owns itExample
Your codeRepositories and servicesYouorders.save(order)
Spring Data JPAGenerates repository implementations on top of JPASpring teamJpaRepository<Order, Long>
JPAA specification: annotations and interfacesJakarta EE@Entity, EntityManager
Hibernate ORMThe implementation of that specificationRed Hat and communitySessionFactory, the SQL generator
JDBC driverSpeaks the database's wire protocolDatabase vendorPostgreSQL JDBC

Each layer talks only to the one below it. Your code never calls Hibernate directly in a typical Spring Boot project; you call a Spring Data repository, which calls a JPA EntityManager, which is a Hibernate object under the surface. The bottom of the stack is covered in the JDBC tutorial, and the whole stack's day-to-day use in the Hibernate and JPA guide.

The specification

JPA, now Jakarta Persistence, is a document and a set of API classes. The document says what persist means, how the persistence context behaves and what the query language accepts. The jar contains only interfaces, annotations and a bootstrap mechanism; there is no code in it that can talk to a database.

Everything in the package jakarta.persistence belongs to the specification:

src/main/java/dev/javahacks/shop/Product.javajava
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "product")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 120)
    private String name;

    protected Product() { }

    public Product(String name) {
        this.name = name;
    }
}

Every import starts with jakarta.persistence, so this entity runs on any compliant provider. The same specification is why the old package was javax.persistence until the namespace change described in the Java EE to Jakarta EE rename. The specification text is at jakarta.ee/specifications/persistence.

The implementation

Hibernate ORM is a library that implements the specification and adds a lot more. When the application starts, something has to turn @Entity into SQL and a connection into a session. That is Hibernate's code. You can see which implementation is behind a JPA object by asking:

java
@Autowired
EntityManager em;

void whoAmI() {
    System.out.println(em.getClass().getName());
    System.out.println(em.getDelegate().getClass().getName());
    org.hibernate.Session session = em.unwrap(org.hibernate.Session.class);
    System.out.println(session.getSessionFactory().getClass().getSimpleName());
}
Text
jdk.proxy2.$Proxy132
org.hibernate.internal.SessionImpl
SessionFactoryImpl

The EntityManager your code sees is a Spring-managed proxy; the delegate is Hibernate's SessionImpl. unwrap is the supported escape hatch from the standard API to the implementation's richer one.

Hibernate offers features the specification does not require. Those live in the package org.hibernate, and using them ties a class to Hibernate:

java
import jakarta.persistence.*;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.NaturalId;

@Entity
public class Order {

    @Id @GeneratedValue
    private Long id;

    @NaturalId                                 // Hibernate only
    private String reference;

    @OneToMany(mappedBy = "order")
    @BatchSize(size = 25)                      // Hibernate only: fetch tuning
    private List<OrderLine> lines = new ArrayList<>();
}

A rule of thumb: an annotation from jakarta.persistence is portable, one from org.hibernate.annotations is Hibernate. In practice almost every real project uses a few of the second kind, and that is fine; the point is to know which you used. Other providers exist (EclipseLink is the reference implementation of the specification), and a project that stays strictly on the standard API can switch, although few ever do. The Hibernate documentation is at hibernate.org/orm.

The Spring layer

Spring does two things on top. Spring Boot's auto-configuration builds the EntityManagerFactory, a DataSource and a transaction manager from your properties and classpath, so you write no bootstrap code. Spring Data JPA turns an interface into a working repository:

src/main/java/dev/javahacks/shop/ProductRepository.javajava
public interface ProductRepository extends JpaRepository<Product, Long> {

    List<Product> findByNameContainingIgnoreCase(String fragment);
}

There is no implementation class. Spring Data generates one at startup, whose methods call EntityManager.persist, find and the query API underneath. Add the starter and Boot supplies everything, including Hibernate as the default provider:

pom.xmlXML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

That single dependency brings in Spring Data JPA, the Jakarta Persistence API and Hibernate ORM. Check with the dependency tree:

Shell
./mvnw dependency:tree -Dincludes=org.hibernate.orm,jakarta.persistence
Text
\- org.springframework.boot:spring-boot-starter-data-jpa:jar:4.0.0:compile
   +- org.hibernate.orm:hibernate-core:jar:7.1.0.Final:compile
   \- jakarta.persistence:jakarta.persistence-api:jar:3.2.0:compile

The versions come from the Boot BOM, which is why you should not set them yourself.

Why the distinction matters in practice

Knowing the layers pays off in four everyday situations.

Reading error messages. jakarta.persistence.PersistenceException and TransactionRequiredException are the standard's. org.hibernate.LazyInitializationException and org.hibernate.exception.ConstraintViolationException are Hibernate's. Spring then wraps them in its own DataAccessException hierarchy. The class prefix tells you which layer is complaining and which documentation to open.

Reading documentation. Questions about @Entity semantics, EntityManager behavior and JPQL are answered in the specification. Questions about batch fetching, second-level caches, @Formula, the statistics API and SQL logging are Hibernate's. Searching for the wrong one wastes an hour.

Tuning and configuration. Properties starting with spring.jpa. are Spring Boot's. Properties starting with hibernate. are passed through to Hibernate (spring.jpa.properties.hibernate.jdbc.batch_size=50). Properties starting with jakarta.persistence. are standard. A property placed in the wrong namespace is silently ignored.

Performance problems. The famous ones, N+1 selects and lazy loading surprises, are behaviors of the persistence provider acting on your mappings, as laid out in the N+1 problem and how to fix it. The spec defines FetchType.LAZY; Hibernate decides how to implement the proxy. You cannot tune what you misattribute.

How the versions line up

The layers move together, and a mismatch is a common source of errors after an upgrade. Spring Boot 4 manages Spring Data JPA 4, Hibernate ORM 7 and Jakarta Persistence 3.2 as one set, and the Boot BOM is the source of truth for which versions fit. If you override only Hibernate, for example to pick up a bug fix, check that the release still implements the Jakarta Persistence version Spring Data expects; a provider older than the specification the repository layer targets fails at startup with a NoSuchMethodError or a missing class from jakarta.persistence. Pin versions in one place, the BOM, and read the migration notes of each layer when you move a major version, because a Hibernate major release can change query semantics and defaults even when your entities compile unchanged.

Where the stack is overkill

The whole stack is a tool for object graphs with relationships that change in transactions. If your service mostly runs reporting queries, bulk loads or a handful of hand-tuned statements, an ORM adds a persistence context you do not need. JdbcClient or a SQL-first library fits better there, and nothing stops you from using both in one application: JPA for the entities that change, SQL for the reads. If you only ever read a table into records, you lose nothing by skipping JPA for that module.

In short: JPA is what you write against, Hibernate is what runs, Spring Data is how you avoid boilerplate, and JDBC is where it all ends up. Keep to the standard where it is enough and reach into Hibernate on purpose where it is not.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.