Sub topic 1
What JPA, Hibernate and Spring Data JPA each do
Prerequisites
This chapter assumes you know the following:
- Core Java: classes, generics, interfaces and annotations.
- Basic SQL and relational modeling: tables, primary keys, foreign keys and joins.
- Basic Spring Boot: beans, dependency injection and application properties.
You don't need any JPA experience. This chapter gives you the working model that the later chapters build on.
The problem: objects and tables don't match
Java programs work with objects. Relational databases work with rows in tables. The two models differ in several ways, and this gap is often called the object-relational impedance mismatch.
- Identity. Two Java objects are the same if they share a reference. Two rows are the same if they share a primary key.
- Relationships. An object holds a reference to another object, or a list of them. A row holds a foreign key value, and the "many" side holds the key.
- Navigation. In Java you write
author.getBooks(). In SQL you write a join or a second query. - Types. A Java
Stringor enum has no single obvious column type. A table has no concept of inheritance.
Without help, you write JDBC code by hand. You open a connection, build SQL strings, set parameters, read a ResultSet and copy each column into a field. This is repetitive, and mistakes in it are easy to make.
An object-relational mapper (ORM) is a library that automates this translation. You describe how classes map to tables, and the ORM generates the SQL and fills in the objects.
Three layers, three jobs
Three names appear in almost every Spring persistence project. They are related, but they are not interchangeable.
| Name | What it is | What it does |
|---|---|---|
| JPA (Jakarta Persistence) | A specification | Defines the annotations (`@Entity`, `@Id`), the `EntityManager` API and the query language JPQL. It contains no real implementation. |
| Hibernate | A JPA provider (implementation) | Does the actual work: generates SQL, manages the persistence context, handles lazy loading and caching. |
| Spring Data JPA | A Spring library on top of JPA | Generates repository implementations from interfaces, so you rarely call the `EntityManager` directly. |
JPA: the contract
JPA is a standard. It was formerly called Java Persistence API, and since version 3.0 it lives in the jakarta.persistence package (earlier versions used javax.persistence). The specification describes:
- Mapping annotations that link classes and fields to tables and columns.
- The
EntityManagerinterface, which you use to save, find and remove entities. - JPQL, a query language that works on entities and their fields instead of tables and columns.
- Rules for entity lifecycle states and transactions.
Because JPA is only a specification, code that uses only jakarta.persistence types can in principle run on any provider, such as Hibernate or EclipseLink.
Hibernate: the engine
Hibernate is the JPA provider that Spring Boot configures by default. At runtime it:
- Reads your mapping annotations and builds metadata about each entity.
- Translates JPQL and entity operations into SQL for your specific database dialect.
- Tracks which entities it has loaded and which of them changed.
- Creates proxy objects so that associations can load lazily.
- Writes pending changes to the database when a transaction commits, or earlier when needed.
Hibernate also offers features beyond the specification, such as extra annotations. Using those ties your code to Hibernate. Later chapters point this out where it matters.
Spring Data JPA: the convenience layer
Spring Data JPA does not replace Hibernate. It sits above JPA and removes boilerplate. You declare an interface, and Spring creates an implementation at startup.
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}This one declaration gives you methods such as save, findById, findAll, count and deleteById. Spring Data also reads method names to build queries, which later chapters cover under derived query methods. Internally, the generated repository calls an EntityManager, and Hibernate does the rest.
How the layers fit together
A call from your code passes through each layer in order.
Your code only touches the top of this stack in most cases. When something goes wrong, such as an unexpected SQL statement or a lazy loading error, the cause usually lives lower down. Knowing which layer owns which behavior tells you where to look.
| Symptom | Layer that owns it |
|---|---|
| Method `findByTitle` becomes a query | Spring Data JPA |
| `@Entity` is ignored or a table is missing | JPA mapping, read by Hibernate |
| Extra `select` statements for each row | Hibernate fetching behavior |
| `LazyInitializationException` | Hibernate, outside an open session |
| Connection errors | JDBC driver and connection pool |
A first look at the working model
Here is a minimal entity. The annotations are JPA, so they come from jakarta.persistence.
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
protected Book() {
}
public Book(String title) {
this.title = title;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
}With the repository above, a service can save and load books without any SQL:
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BookService {
private final BookRepository books;
public BookService(BookRepository books) {
this.books = books;
}
@Transactional
public Long create(String title) {
Book saved = books.save(new Book(title));
return saved.getId();
}
@Transactional(readOnly = true)
public String titleOf(Long id) {
return books.findById(id).orElseThrow().getTitle();
}
}Each layer contributes here:
@Entityand@Idare JPA annotations that describe the mapping.- Hibernate turns
saveinto aninsertstatement and reads the generated key back. - Spring Data JPA supplies
saveandfindByIdwithout you writing an implementation. - Spring's
@Transactionalopens and commits the transaction around the method.
Common misunderstandings
- "Spring Data JPA is an ORM." It is not. It generates repository code. The ORM work happens in the JPA provider, which is Hibernate by default.
- "JPA is a library I add." JPA is an API. You need a provider on the classpath. The
spring-boot-starter-data-jpastarter brings in Hibernate for you. - "
savealways runs aninsert."savecallspersistfor a new entity andmergefor an existing one. Whether SQL runs at that moment depends on the identifier strategy and the transaction. Later chapters on identifiers and the persistence context explain this. - "Repositories hide the database." They hide boilerplate, not behavior. Transactions, fetch strategies and SQL cost still matter, and you must understand them.
- Mixing
javaxandjakarta. Spring Boot 3 and later usejakarta.persistence. Imports fromjavax.persistencewill not compile against these versions.
When Spring Data JPA is a good fit
Spring Data JPA works well for applications that model a domain as entities and need mostly create, read, update and delete operations plus filtered queries. Weigh these trade-offs before choosing it:
- Strength. Little code for common operations, and queries are checked at startup for derived methods and JPQL.
- Cost. The persistence context and lazy loading add concepts you must learn.
- Limit. Reports with complex SQL, bulk operations and heavy tuning often need native queries or another tool such as JDBC templates or jOOQ.
You can combine these tools in one application. The chapters that follow cover each part of this stack in turn: setup, entity mapping, identifiers, associations, repositories, queries, the persistence context, fetching, projections, equality, auditing and testing.
Exercise
A teammate says, "We use Spring Data JPA, so we don't need Hibernate." Using the three layers described in this chapter, explain what is wrong with this statement, and name which layer generates the SQL.
Show answer
Spring Data JPA does not talk to the database by itself. It generates repository implementations that call the JPA EntityManager. JPA is only a specification, so a provider must implement it. In a default Spring Boot project that provider is Hibernate, which spring-boot-starter-data-jpa adds to the classpath. Hibernate generates the SQL and sends it through JDBC. Without a provider, the repositories would have nothing to run on.
Exercise
A repository method named findByTitle fails at startup, saying that no property title was found on the entity. Which layer reads the method name, and which layer supplied the entity metadata it checks against?
Show answer
Spring Data JPA reads the method name and tries to build a query from it. It checks the property name against the entity metadata, which comes from the JPA mapping that Hibernate reads. So the entity probably has no field named title, or has a differently spelled one. Fix the method name or the field name.