How Spring Data JPA, JPA, and Hibernate Work Together
What Spring Data JPA, JPA, and Hibernate Actually Do#
Spring Data JPA is a Spring Framework module that lets Java backend developers query a relational database without writing SQL, by generating database access code from annotated interfaces at startup. When you call userRepository.findByEmail(email) and get back a User object, there is no SQL in your code, no connection management, no result-set iteration, and no manual mapping from rows to fields.
Three separate pieces of technology ran on your behalf in that single line of code, and they do very different jobs. Spring Data JPA saw your method name and generated a complete repository implementation at startup. JPA provided the standard contracts that the generated code speaks. Hibernate took those contracts, built the SQL, sent it to the database, and mapped the result back to your User class. Each layer contributed something the others did not.
Spring Data JPA, JPA, and Hibernate are three distinct layers. This distinction matters more than it might seem. When a query returns stale data, or a LazyInitializationException surfaces in production, or a derived method stops matching what you intended, the fix lives in a specific layer. The goal of Spring Data JPA is to simplify the development of a JPA-based data access layer and it genuinely succeeds at that. The cost is that the layers become invisible, which makes them harder to reason about when something goes wrong.
Hibernate: The Engine Doing the Real Work#
Hibernate is an ORM (Object-Relational Mapping) framework. It generates SQL statements and maps the resulting database rows back to Java objects, handling the fundamental mismatch between how relational databases think (tables, rows, foreign keys) and how Java programs think (objects, references, inheritance).1, 2 When you hear "Hibernate does the SQL," that is literally true. No other layer in the stack generates the SELECT, INSERT, UPDATE, or DELETE statements. Spring Data JPA and JPA itself both eventually hand off to Hibernate for this.
At the center of Hibernate's model is the Session. Each Session represents a single unit of work and owns a persistence context: an in-memory map of every entity instance it has loaded or saved. When you load a User by ID, Hibernate places that object in the persistence context. If you then modify a field on that object within the same session, Hibernate detects the change automatically and issues an UPDATE at flush time, without you writing any SQL at all.
To appreciate what Hibernate removes from your codebase, consider what a simple lookup looks like in raw JDBC:
With Hibernate and a @Entity-annotated User class, the equivalent is one line:
Hibernate reads the entity's annotations, derives the table and column names, builds the SQL, executes it, and constructs the object. Every column mapping, every type conversion, every relationship join is handled according to what you declared on the class.
When used directly with Spring, the integration goes through LocalSessionFactoryBean and HibernateTransactionManager, which wire Hibernate's Session lifecycle into Spring's transaction management.3 @Transactional methods get a properly scoped session, and the session flushes and closes when the transaction commits.
Hibernate is genuinely powerful at this level. The cost is that its native API is vendor-specific: your code calls SessionFactory, Session, and Criteria types that belong to Hibernate itself. Switch to a different ORM and you rewrite those call sites. That is exactly the problem JPA was designed to solve.
JPA: The Standard Contract That Makes Hibernate Swappable#
Any software engineer who has worked with interfaces and implementations will recognize the relationship immediately: JPA is the interface, and Hibernate is one implementation of it.
JPA (Jakarta Persistence API) is a specification rather than a library, meaning the jakarta.persistence package ships no SQL-generation code of its own.2 It defines a contract: a set of annotations, interfaces, and rules that any conforming ORM must honour. Hibernate has been the dominant implementation since JPA's early days, but EclipseLink is another fully compliant provider. Because the specification standardizes the API, an application coded against JPA can, in principle, swap Hibernate for EclipseLink by changing a configuration property without touching a single line of persistence logic.
The practical difference shows up most clearly when you compare operations side by side. Hibernate has its own native API (Session, Transaction, SessionFactory) that predates JPA; the JPA equivalents (EntityManager, EntityTransaction, EntityManagerFactory) cover the same ground with a portable surface:
| Operation | Hibernate Native API | JPA API |
|---|---|---|
| Begin transaction | session.beginTransaction() | em.getTransaction().begin() |
| Load by ID | session.get(User.class, id) | em.find(User.class, id) |
| Persist new entity | session.save(entity) | em.persist(entity) |
| Close context | session.close() | em.close() |
When Hibernate runs beneath JPA, it implements every one of those EntityManager calls. The SQL generation, dirty checking, and caching described above still happen inside Hibernate; JPA standardizes what you call to trigger them.
The central abstraction JPA gives you is the EntityManager. You mark a class with @Entity and a field with @Id, and the EntityManager takes responsibility for tracking that object's lifecycle: persisting it, merging detached changes, removing it, and querying for it using JPQL (Java Persistence Query Language). JPQL looks like SQL but operates on entity class names and field names rather than table and column names, so it stays portable across databases the same way the rest of the JPA contract does.
Working directly with EntityManager still involves a fair amount of boilerplate. Every operation typically requires obtaining an EntityManager from the factory, managing the transaction boundary manually, handling exceptions, and closing the context. The annotations on your entities take care of the mapping, but the surrounding plumbing stays repetitive. Spring Data JPA closes that gap by wrapping the EntityManager in a repository abstraction that reduces a full CRUD surface to a single interface declaration.
Diagram as text
flowchart LR App["Application Code"] EM["EntityManager\n(JPA API)"] JPA["JPA Specification"] Hibernate["Hibernate\n(JPA Provider)"] EclipseLink["EclipseLink\n(JPA Provider)"] App -->|"calls"| EM EM -->|"defined by"| JPA JPA -->|"implemented by"| Hibernate JPA -->|"implemented by"| EclipseLink
Spring Data JPA: The Repository Layer That Writes Itself#
Consider the following interface:
There is no implementation class. No SQL. No EntityManager calls. Yet when you inject UserRepository into a service and call findByEmail("alice@example.com"), it runs a database query and returns a result.
This is what Spring Data JPA contributes to the stack: it reads your repository interface at startup, inspects every method signature, generates a concrete proxy implementation, and registers it as a Spring bean. That proxy calls through to JPA's EntityManager, which in turn delegates to Hibernate. You write the contract; Spring Data JPA writes the code.
What JpaRepository gives you for free#
Extending JpaRepository<User, Long> immediately makes a set of standard methods available: save, findById, findAll, delete, count, and several others, including paginated and sorted variants. You do not declare these; they are pulled in from the interface hierarchy. JpaRepository extends PagingAndSortingRepository, which itself extends CrudRepository, so the full set of CRUD operations and pagination support arrives together.
Derived query methods#
Beyond the built-in methods, Spring Data JPA can generate queries from method names you declare yourself. The name findByEmail tells Spring Data to produce a JPQL query filtering by the email field.4 The parser understands a broad vocabulary: findByNameContaining, findByAgeLessThan, findByActiveIsTrue, findByDepartment_Name, and so on.4, 4 You can combine conditions with And and Or, add Top5 or Distinct, and attach a Pageable or Sort parameter to control pagination automatically.4, 4
When the naming convention is not enough, the @Query annotation lets you write JPQL or native SQL directly on the method, keeping the same zero-boilerplate invocation style.
Auto-configuration in Spring Boot#
In a Spring Boot application, none of this requires explicit wiring. When spring-boot-starter-data-jpa is on the classpath, Boot's auto-configuration detects it and enables JPA repository scanning automatically. You do not need @EnableJpaRepositories in most projects; Boot infers the base packages from your main application class. If you need to customize scan locations or register a custom repository base class, adding @EnableJpaRepositories explicitly gives you that control.
The delegation chain#
When your service calls userRepository.findByEmail(email), the proxy generated by Spring Data JPA translates that method name into a JPQL query string and hands it to an EntityManager. The EntityManager passes the query to Hibernate, which generates the SQL, executes it against the database, and maps the result rows back to User objects. Spring Data JPA eliminates the boilerplate at the top of this chain; everything below it still runs.
In practice, a backend developer can add a new query to a repository in one line and never touch an EntityManager, a Session, or a SQL string. The trade-off is that the method name parser has limits: deeply complex queries, window functions, or multi-table aggregations typically need @Query or a custom repository fragment. Knowing where the naming convention ends and explicit queries begin is the next practical skill worth developing.
How the Three Layers Collaborate on a Single Query#
Consider this service call against a separate illustrative repository using a UUID primary key, to show how the same layering applies regardless of entity type:
When staffRepository.findByEmail(email) is called at runtime, the call passes through all three layers in a predictable sequence.5
- Spring Data JPA proxy parses the method name to JPQL. Spring Data generates a runtime proxy for
StaffRepository. WhenfindByEmailis invoked, the proxy inspects the method name, recognizes thefindByintroducer and theEmailcriteria, and constructs a JPQL query such asSELECT s FROM Staff s WHERE s.email =:email.4 - EntityManager receives the JPQL. The proxy delegates execution to the JPA
EntityManager, passing the generated JPQL and the bound parameter. - Hibernate translates JPQL to dialect SQL. The
EntityManagerforwards the query to Hibernate, which reads the JPQL, consults the configured database dialect, and generates the appropriate SQL: for PostgreSQL something likeSELECT staff_id, email,... FROM staff WHERE email = $1. - JDBC executes the SQL. Hibernate sends that SQL to the underlying JDBC driver, which submits it to the database and retrieves a
ResultSet. - Hibernate maps the ResultSet to an entity. Hibernate reads the returned rows and hydrates
Staffentity objects. If the persistence context already holds aStaffwith the same primary key from an earlier load within the same transaction, Hibernate returns the cached instance rather than creating a duplicate. - **
Optional<Staff>returns to the service.** Spring Data wraps the result and hands it back up the call chain.5
The diagram below illustrates these six steps as a layered call flow.
Diagram as text
flowchart TD
Caller["Caller"]
Proxy["Spring Data JPA Proxy\n— derives JPQL from method name —"]
EM["JPA EntityManager\n— standard persistence API —"]
HS["Hibernate Session\n— translates JPQL to SQL dialect —"]
DB[("Database")]
ResultSet["ResultSet returned"]
MapEntity["Hibernate maps rows to entity"]
IdentityMap["Identity map check\n— first-level cache —"]
ReturnCaller["Entity returned to Caller"]
Caller -->|"findByEmail()"| Proxy
Proxy -->|"JPQL query"| EM
EM -->|"delegates to provider"| HS
HS -->|"SQL via JDBC"| DB
DB --> ResultSet
ResultSet --> MapEntity
MapEntity --> IdentityMap
IdentityMap --> ReturnCallerEach layer has a clearly bounded job. Spring Data JPA handles boilerplate around query creation and result wrapping. JPA provides the portable EntityManager API that decouples your code from any particular ORM. Hibernate does the work of translating object-level intent into SQL and back into objects.
That boundary also tells you where to look when things break. A PropertyReferenceException at startup usually means Spring Data could not parse the method name: layer one. A query that runs but returns wrong data often points to Hibernate's SQL generation or mapping: layer three. An EntityNotFoundException or an unexpected empty result on a second load within a transaction points to the persistence context identity map, also Hibernate's territory.
Matching a Symptom to the Layer That Owns It#
Why is your app sending 100 queries for 10 users? The answer almost always lives in exactly one of the three layers, and knowing which one saves a lot of time staring at the wrong configuration file.
N+1 queries: Hibernate's fetch strategy
The N+1 problem originates in Hibernate. When a collection association is mapped with lazy loading (the default for @OneToMany), Hibernate issues one SQL SELECT to fetch the parent entities and then one additional SELECT per parent to fetch each child collection when it is accessed.1 Ten users means eleven queries. A hundred users means a hundred and one.
The fix lives in Hibernate's fetch configuration. Switching the association to FetchType.EAGER often trades one problem for another. The more surgical approach is a JOIN FETCH in a JPQL query, or using @EntityGraph to declare which associations to load eagerly for a specific operation while leaving the default behavior unchanged everywhere else.6
LazyInitializationException: JPA session scope
LazyInitializationException is thrown by Hibernate when code tries to access a lazily-loaded association after the JPA EntityManager (and its persistence context) has already been closed.7 This is a session-scope problem, not a Spring Data JPA problem. The repository did its job; the session closed before the caller finished reading the entity.
The concrete scenario: a service method loads an Employee, the transaction closes, the EntityManager closes with it, and then a serializer or controller tries to access employee.getLeaves(). That collection is a Hibernate proxy with no open session to issue the lazy SELECT against.7
The clean fix is to ensure all lazy access happens inside the transaction boundary, typically by keeping the data access and association traversal inside a @Transactional service method, or by converting entities to DTOs before the session closes. Spring Boot enables spring.jpa.open-in-view=true by default, which keeps the session open through the web layer, but this is generally considered an anti-pattern because it holds database connections longer than necessary.7
Unexpected query results: Spring Data JPA method name parsing
When a repository method returns the wrong data without throwing an exception, the issue is in the Spring Data JPA layer: the method name resolved to a different predicate than you expected. Spring Data JPA parses method names at startup and translates them into JPQL queries, but a subtly misspelled property name or an ambiguous keyword can produce a valid-but-wrong query.
The fastest diagnostic is enabling SQL logging with spring.jpa.show-sql=true in application.properties.8 You can see the actual SQL Hibernate executes and compare it against what you intended. If the generated query is wrong, the fix is either to correct the method name or to replace the derived query with an explicit @Query annotation.
| Symptom | Owning Layer | Root Cause | Fix |
|---|---|---|---|
| Too many SQL SELECTs in logs | Hibernate | LAZY association accessed in loop | JOIN FETCH or @EntityGraph |
LazyInitializationException at serialization | JPA (EntityManager scope) | Proxy accessed after session closes | Load within @Transactional; use DTOs |
| Method returns wrong rows silently | Spring Data JPA | Method name parsed to wrong predicate | Enable show-sql, correct name or add @Query |
When something breaks, the stack trace and log tell you where to look. If the problem is SQL-shaped (wrong queries, too many queries), look at Hibernate fetch strategies and entity mappings. If it is session or transaction-shaped (LazyInitializationException, detached entity errors), look at the JPA EntityManager lifecycle and your @Transactional boundaries. If it is method or API-shaped (wrong results, unexpected filtering), look at the Spring Data JPA repository and what query it actually generated.
Enabling spring.jpa.show-sql=true will usually point you directly at which layer misfired.
Sources
- Hibernate :: Spring Frameworkdocs.spring.io
- Introduction to ORM with Spring :: Spring Frameworkdocs.spring.io
- Integrating Jakarta Data with Spring: Rinse and Repeat | by Hantsy | ITNEXTitnext.io
- Spring Data JPA Derived Queries - CodingNomadscodingnomads.com
- Spring Data JPA: Exploring derived query methods and @Query search options | Mediumeuedofia.medium.com
- Fixing the N+1 Query Problem in JPA with Fetch Joins and EntityGraphprometheanz.com
- Spring Boot Lazy Initialized Entitieslinkedin.com
- SQL Databases :: Spring Bootdocs.spring.io
Keep reading
Tuning HikariCP in Spring Boot for High-Throughput Database Performance
HikariCP is Spring Boot's default JDBC connection pool. It maintains a fixed set of pre-opened database connections that application threads borrow, use, and return, eliminating...
What a forward deployed engineer does, and how to prepare
A forward deployed engineer is a software engineer who works inside the customer's organization rather than inside the product team. The job is to build and ship custom solutions...
Chain of Thought or ReAct: Choosing Between Them
A support queue needs priorities. Every incoming ticket has to carry a label, P1 through P4, before it reaches a human, and you have been handed the feature. Two implementations...