JPA, Hibernate and Spring Data JPA
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Tutorials mix up JPA, Hibernate and Spring Data JPA, yet a ShopLite repository call passes through all three before it reaches MySQL. Knowing who does which job tells you where to look when something breaks.
JPA is a specification
JPA (Jakarta Persistence, version 3.2 in Spring Boot 4.1) is a specification: interfaces and annotations in jakarta.persistence that say how Java objects map to tables. It holds no working code; a provider such as Hibernate supplies that.
Example 1 loads a ShopLite category with the JPA EntityManager and with a JPQL query. Only jakarta.persistence types appear; the log shows the SQL the provider wrote.
Example 1 · Plain JPA: EntityManager.find and a JPQL query
Runs in: the jpa-lab Spring Boot project with the ShopLite database
// src/main/java/com/shoplite/lab/em/EntityManagerDemo.java (the first half of run)private final EntityManager entityManager; // jakarta.persistence.EntityManager
Category mobiles = entityManager.find(Category.class, 2);System.out.println("find(2): " + mobiles.getName());
List<Category> children = entityManager .createQuery("SELECT c FROM Category c WHERE c.parentId = :parent ORDER BY c.name", Category.class) .setParameter("parent", 1) .getResultList();System.out.println("Under Electronics: " + children.stream().map(Category::getName).toList());$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=em --logging.level.org.hibernate.SQL=DEBUG
...
2026-10-16T12:20:42.344+05:30 DEBUG 26456 --- [jpa-lab] [ main] org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
find(2): Mobiles
2026-10-16T12:20:43.745+05:30 DEBUG 26456 --- [jpa-lab] [ main] org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.parent_id=? order by c1_0.name
Under Electronics: [Accessories, Laptops, Mobiles]What this code does
find(Category.class, 2)loads by primary key. JPA knows which table and columns from the@Entitymapping, so Hibernate writes the SELECT you see in the log.- The JPQL query names the class
Categoryand the fieldparentId. Hibernate translates them to the tablecategoriesand the columnparent_id, and:parentbecomes a?parameter. - Only
jakarta.persistencetypes appear in this code; nothing here mentions Hibernate. (--lab.demo=emis a lab-only switch that picks this runner.)
The package holds annotations such as @Entity, @Id and @Column, and the EntityManager interface you use to load and save entities. EntityManager is only an interface, like List; a JPA provider implements it, the way ArrayList implements List. Why a specification? Code written against jakarta.persistence can, in principle, switch providers, and every provider is tested against the same rules.
JPA also defines JPQL, a query language written against classes and fields (SELECT c FROM Category c WHERE c.parentId = :parent), not tables and columns. The provider translates it into SQL for your database, as the log in Example 1 shows.
Hibernate 7: the implementation Spring Boot uses
Hibernate ORM is the JPA provider Spring Boot 4.1 uses by default. It reads your mapping at startup, writes SQL for MySQL, runs it through JDBC and turns rows into objects. Boot 4.1.1 brings Hibernate 7.4.
Hibernate 7 and Spring Boot 4 know only the jakarta.persistence package. Example 2 shows what an old javax.persistence import does to a ShopLite class.
Example 2 · Old javax.persistence imports in a Spring Boot 4 project
Runs in: the jpa-lab Spring Boot project
// src/main/java/com/shoplite/lab/old/OldCategory.java (copied from a Spring Boot 2 tutorial)package com.shoplite.lab.old;
import javax.persistence.Entity;import javax.persistence.Id;
@Entitypublic class OldCategory {
@Id private Integer id;}$ mvn compile
...
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/Users/asha/projects/jpa-lab/src/main/java/com/shoplite/lab/old/OldCategory.java:[3,25] package javax.persistence does not exist
[ERROR] /C:/Users/asha/projects/jpa-lab/src/main/java/com/shoplite/lab/old/OldCategory.java:[4,25] package javax.persistence does not exist
[ERROR] /C:/Users/asha/projects/jpa-lab/src/main/java/com/shoplite/lab/old/OldCategory.java:[6,2] cannot find symbol
symbol: class Entity
[ERROR] /C:/Users/asha/projects/jpa-lab/src/main/java/com/shoplite/lab/old/OldCategory.java:[9,6] cannot find symbol
symbol: class Id
location: class com.shoplite.lab.old.OldCategory
[INFO] 4 errors
[INFO] BUILD FAILUREWhat this code does
- Spring Boot 4.1 brings
jakarta.persistence-api3.2; nojavax.persistencepackage is on the classpath at all, so the compiler cannot findEntityorId. - The fix is the import line only:
jakarta.persistence.Entityandjakarta.persistence.Id. The annotation names and their meaning did not change. - Seeing
javax.persistencein an article tells you it was written for Spring Boot 2 or older; check the rest of it for other outdated parts too.
EclipseLink is another JPA provider, used less often with Spring. The dialect decides MySQL's flavour of SQL. Hibernate is older than JPA and offers more: its own Session API and extra annotations in org.hibernate.annotations. Behind the EntityManager you inject sits a Hibernate SessionImpl (Example 3 prints it).
In 2019 Java EE moved to the Eclipse Foundation and became Jakarta EE, and the package names changed from javax.persistence to jakarta.persistence. Spring Boot 3 and later, and Hibernate 6 and later, use only the new names, so code copied from an old tutorial fails to compile, as Example 2 shows.
Fix the error
Fix the JPA import
Read the real error, then pick the line that fixes it.
Round 1 of 2
A ShopLite entity copied from an old tutorial no longer compiles.
Error
Category.java:3: error: package javax.persistence does not exist
import javax.persistence.Entity;
^Spring Data JPA: you write the interface, Spring writes the class
Spring Data JPA is a Spring project on top of JPA that creates repository objects from interfaces such as CategoryRepository extends JpaRepository<Category, Integer>. You get findById, findAll, save and count without writing a class.
ShopLite declares only an interface. Example 3 prints who really answers a findById call at runtime.
Example 3 · A Spring Data repository: who is who at runtime
Runs in: the jpa-lab Spring Boot project with the ShopLite database
// src/main/java/com/shoplite/lab/category/CategoryRepository.javapackage com.shoplite.lab.category;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoryRepository extends JpaRepository<Category, Integer> {}
// src/main/java/com/shoplite/lab/em/EntityManagerDemo.java (the second half of run)System.out.println("findById(2): " + categories.findById(2).map(Category::getName).orElse("none"));
System.out.println("EntityManager class: " + entityManager.getClass().getName());System.out.println("Real object behind it: " + entityManager.getDelegate().getClass().getName());System.out.println("Repository class: " + categories.getClass().getName());System.out.println("Does the work: " + AopUtils.getTargetClass(categories).getName());System.out.println("Hibernate version: " + Version.getVersionString());... 2026-10-16T12:20:43.807+05:30 DEBUG 26456 --- [jpa-lab] [ main] org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? findById(2): Mobiles EntityManager class: jdk.proxy2.$Proxy98 Real object behind it: org.hibernate.internal.SessionImpl Repository class: jdk.proxy2.$Proxy102 Does the work: org.springframework.data.jpa.repository.support.SimpleJpaRepository Hibernate version: 7.4.5.Final
What this code does
CategoryRepositoryhas no methods of its own, yetfindByIdworks and sends the same SELECT asentityManager.findin Example 1.- The repository is a runtime proxy (
$Proxy102) whose real work is done bySimpleJpaRepository. The injectedEntityManageris also a Spring proxy; the object behind it is Hibernate'sSessionImpl. - Proxy numbers such as
$Proxy102differ from run to run; the class namesSimpleJpaRepositoryandSessionImpldo not.
The object behind the interface is a proxy: a class generated at runtime (jdk.proxy2.$Proxy102 in Example 3) that passes each call to Spring Data's SimpleJpaRepository, which in turn calls the EntityManager. Your service depends only on the interface, so it is easy to test and to read.
So the three names are three layers: JPA is the API, Hibernate implements it, and Spring Data JPA removes the repetitive repository code on top. One app uses all three, mostly through Spring Data.
The full stack: from controller to MySQL
A request such as GET /api/v1/categories/2 travels down a fixed chain of layers and comes back up with the data. Example 4 reads that chain from a real stack trace, caller first.
Example 4 · Reading the layers from a real stack trace
Runs in: the jpa-lab Spring Boot project with the ShopLite database
// src/main/java/com/shoplite/lab/layers/MissingTableRepository.javapackage com.shoplite.lab.layers;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;
import com.shoplite.lab.category.Category;
interface MissingTableRepository extends JpaRepository<Category, Integer> {
@Query(value = "SELECT * FROM category_list", nativeQuery = true) List<Category> findFromMissingTable();}
// src/main/java/com/shoplite/lab/layers/LayersRunner.javapackage com.shoplite.lab.layers;
import java.util.ArrayList;import java.util.Collections;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
/** * Sends one query that MySQL rejects, then prints which layers the call went through, * read from the stack trace of the driver's exception (caller at the top). */@Componentclass LayersRunner implements CommandLineRunner {
private static final List<String[]> LAYERS = List.of( new String[] {"com.shoplite.lab.layers.LayersRunner", "your code"}, new String[] {"org.springframework.data.", "Spring Data JPA"}, new String[] {"org.springframework.orm.jpa.", "Spring ORM (EntityManager proxy)"}, new String[] {"org.hibernate.", "Hibernate"}, new String[] {"com.zaxxer.hikari.", "HikariCP"}, new String[] {"com.mysql.cj.", "MySQL JDBC driver"});
private final MissingTableRepository repository;
LayersRunner(MissingTableRepository repository) { this.repository = repository; }
@Override public void run(String... args) { try { repository.findFromMissingTable(); } catch (RuntimeException ex) { Throwable root = ex; while (root.getCause() != null) { root = root.getCause(); } System.out.println("Spring threw: " + ex.getClass().getSimpleName()); System.out.println("MySQL said: " + root.getMessage()); System.out.println("Layers, from caller to database:"); Map<String, StackTraceElement> nearest = new LinkedHashMap<>(); for (StackTraceElement frame : root.getStackTrace()) { String layer = layerOf(frame.getClassName()); boolean helper = frame.getClassName().contains("$Proxy") || frame.getClassName().contains(".exceptions."); if (layer != null && !helper) { nearest.putIfAbsent(layer, frame); } } List<Map.Entry<String, StackTraceElement>> callerFirst = new ArrayList<>(nearest.entrySet()); Collections.reverse(callerFirst); for (Map.Entry<String, StackTraceElement> e : callerFirst) { StackTraceElement f = e.getValue(); System.out.printf(" %-45s %s.%s%n", e.getKey(), f.getClassName(), f.getMethodName()); } } }
private static String layerOf(String className) { for (String[] layer : LAYERS) { if (className.startsWith(layer[0])) { return layer[1]; } } return null; }}$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=layers
...
2026-10-16T11:16:08.908+05:30 WARN 25552 --- [jpa-lab] [ main] org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1146, SQLState: 42S02
2026-10-16T11:16:08.908+05:30 WARN 25552 --- [jpa-lab] [ main] org.hibernate.orm.jdbc.error : Table 'shoplite.category_list' doesn't exist
Spring threw: InvalidDataAccessResourceUsageException
MySQL said: Table 'shoplite.category_list' doesn't exist
Layers, from caller to database:
your code com.shoplite.lab.layers.LayersRunner.run
Spring Data JPA org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute
Spring ORM (EntityManager proxy) org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke
Hibernate org.hibernate.sql.results.jdbc.internal.DeferredResultSetAccess.executeQuery
HikariCP com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery
MySQL JDBC driver com.mysql.cj.jdbc.ClientPreparedStatement.executeInternalWhat this code does
- The query names a table that does not exist, so MySQL itself rejects it: error 1146,
Table 'shoplite.category_list' doesn't exist. Hibernate logs it as a WARN, and Spring turns it into its ownInvalidDataAccessResourceUsageException. - The runner walks the stack trace of the driver's exception and keeps the frame nearest the database for each layer: your code, Spring Data, Spring's EntityManager proxy, Hibernate, HikariCP's pooled statement, and the MySQL driver.
@Query(..., nativeQuery = true)sends plain SQL through the same stack; the Repositories module covers it. Here it is just a way to make MySQL fail.
Knowing the layers tells you where to look. Access denied comes from MySQL, a pool timeout from HikariCP, a mapping error from Hibernate, and a "No property found" error from Spring Data.
Order of execution
A repository call travels down
Tap the layers in the order a repository call passes through them.
Which import to use
Import mapping annotations and the EntityManager from jakarta.persistence first: they are the standard and work with any provider. The snippet shows which import comes from where.
import jakarta.persistence.Column; // JPA standard: use these firstimport jakarta.persistence.Entity;import jakarta.persistence.EntityManager;import jakarta.persistence.Id;
import org.hibernate.annotations.CreationTimestamp; // Hibernate-only, when JPA has nothing
import org.springframework.data.jpa.repository.JpaRepository; // Spring Data JPA
// import javax.persistence.Entity; // old Java EE name: does not exist in Boot 3 or 4Use org.hibernate.annotations only for a Hibernate-only feature that JPA lacks, such as @CreationTimestamp or @BatchSize; that import ties the class to Hibernate. Never use javax.persistence in a Spring Boot 3 or 4 project.
When your IDE offers several @Id or @Entity classes, pick the jakarta.persistence one. The wrong @Id, for example org.springframework.data.annotation.Id, compiles, but Hibernate 7 stops at startup with Entity 'com.shoplite.lab.Category' has no identifier.
Next step
Check your understanding
11 quick questions