Spring Data JPA & Hibernate
Map entities and relations and avoid N+1 queries.
By Invicly Tech, , in Backend Java Development. About 12 minutes to read.
In short
JPA maps Java classes to tables, and Hibernate is the implementation that generates the SQL. Spring Data JPA adds repository interfaces whose queries are derived from method names.
Explained simply
Writing SQL by hand for every insert, update and select gets repetitive. JPA (Jakarta Persistence API) lets you map a Java class to a table, and then save and load objects instead of writing SQL. Hibernate is the library that does the actual work and generates the SQL.
Spring Data JPA removes even more code. You write an interface such as interface BookRepository extends JpaRepository<Book, Long>, and you immediately get save, findById, findAll, delete and paging, without writing a single method body.
You can add your own queries just by naming methods: findByAuthorAndYearGreaterThan(String author, int year). Spring reads the method name and builds the query at startup. For harder cases you write JPQL, a SQL-like language over your entities, or plain native SQL.
The convenience has a price: it is easy to run many more queries than you think. Loading 100 authors and then touching each author's books can quietly run 101 queries. Learning to see and control the SQL that Hibernate sends is the key skill in this topic.
Press Play on a diagram to walk through it one step at a time.
- 1Repository interface
findByEmail declared, no implementation written
- 2Spring Data proxy
Generates the implementation at runtime
- 3Hibernate EntityManager
Tracks entities and generates SQL
- 4JDBC and pool
Sends SQL over pooled connections
- 5Database
Tables mapped from @Entity classes
- 1 query loads 100 authors
- 100 more load each author's books
- Hidden by lazy loading
- Slow as data grows
- join fetch a.books
- One query loads both
- Or use @EntityGraph
- Check SQL logs to confirm
- Controller loop to Hibernate: authorRepo.findAll()1authorRepo.findAll()
- Hibernate to PostgreSQL: select * from author (100 rows)2select * from author (100 rows)
- Controller loop to Hibernate: author1.getBooks().size()3author1.getBooks().size()
- Hibernate to PostgreSQL: select * from book where author_id=14select * from book where author_id=1
- Controller loop to Hibernate: author2.getBooks().size()5author2.getBooks().size()
- Hibernate to PostgreSQL: select * from book where author_id=26select * from book where author_id=2
- Hibernate to PostgreSQL: ... 98 more queries7... 98 more queries
In depth
Mapping entities properly
An entity needs @Entity, an @Id and a no-argument constructor (it can be protected). For ids in PostgreSQL, @GeneratedValue(strategy = GenerationType.IDENTITY) uses an identity column, which is simple but prevents Hibernate from batching inserts. GenerationType.SEQUENCE with a sequence allows batching and is preferred for bulk inserts.
Use @Column(nullable = false, length = 200) to document constraints, but remember the database schema, created by your migrations, is what really enforces them. Map enums with @Enumerated(EnumType.STRING). The default, ORDINAL, stores 0, 1, 2, so inserting a new constant in the middle silently changes the meaning of existing rows. Set spring.jpa.hibernate.ddl-auto=validate in real environments: Hibernate checks the schema matches the entities but never changes it; Flyway owns the schema.
- @Enumerated(EnumType.STRING), never the ORDINAL default
- ddl-auto: none or validate outside local experiments
- Base equals and hashCode on a stable business key or id carefully
The persistence context and entity states
Inside a transaction, Hibernate keeps a persistence context: a map of every entity it has loaded or saved, at most one object per row. Loading the same id twice returns the same object, without a second query. These entities are managed, and Hibernate watches them. When the transaction commits, it compares each managed entity with its original state and writes UPDATE statements for the changes. This is called dirty checking, and it means you do not need to call save() after changing a managed entity.
When the transaction ends, entities become detached: changes to them are no longer tracked, and touching an unloaded lazy relation throws LazyInitializationException. A new object you create with new is transient until you persist it. Understanding these states explains most surprising JPA behaviour.
- 1Transient
new Book(): Hibernate does not know it
- 2Managed
After persist or find: changes are tracked
- 3Flush and commit
Dirty checking writes INSERT and UPDATE
- 4Detached
Transaction over: no tracking, no lazy loading
- 5Merged or removed
merge copies state back; remove deletes
Relationships without surprises
In a one-to-many pair, the @ManyToOne side holds the foreign key and is the owning side; the @OneToMany(mappedBy = "author") side is only a mirror. Only changes to the owning side are written to the database, so keep both sides in sync with helper methods like addBook(book), which adds to the list and sets book.setAuthor(this).
Watch the defaults. @ManyToOne and @OneToOne are EAGER by default, so loading a list of books also loads every author, often with extra queries. Set fetch = FetchType.LAZY on them. Collections are lazy by default. cascade = CascadeType.ALL plus orphanRemoval = true suits parent-child pairs like an order and its lines. For @ManyToMany use a Set and never cascade removal, because the other side is shared. If the link needs its own data, such as a quantity, model the join table as its own entity.
- @ManyToOne(fetch = FetchType.LAZY) everywhere
- mappedBy marks the non-owning side
- Use helper methods to update both sides
Queries: derived, JPQL, native and projections
Derived queries are built from method names: findByEmail, findByStatusAndCreatedAtAfter, existsBySku, countByStatus, findTop10ByOrderByPriceDesc, deleteByExpiresAtBefore. They are checked at startup, so a typo fails fast. When a name gets long, switch to @Query with JPQL: select o from Order o where o.customer.id = :customerId and o.total > :min. JPQL uses entity and field names, not tables and columns.
For reports, load only what you need. A JPQL constructor expression, select new com.shop.OrderSummary(o.id, o.total) from Order o, fills a record directly, with no entity tracking. Interface projections work too. Use nativeQuery = true for database-specific SQL, such as PostgreSQL JSON operators. Bulk updates with @Modifying @Query("update ...") bypass the persistence context, so loaded entities may be stale afterwards.
Seeing and fixing N+1 queries
First, make queries visible. In development set logging.level.org.hibernate.SQL=debug, or spring.jpa.show-sql=true, and look at the log while you click through a page. If one list request prints dozens of similar SELECTs, you have N+1.
There are several fixes. A fetch join, select a from Author a join fetch a.books, loads parents and children in one query. @EntityGraph(attributePaths = "books") on a repository method does the same without writing JPQL. Setting hibernate.default_batch_fetch_size (spring.jpa.properties.hibernate.default_batch_fetch_size=50) makes Hibernate load lazy collections for many parents at once with IN queries, which is a good global safety net. For read-only screens, a DTO projection avoids the problem entirely. Be careful combining a collection fetch join with paging: Hibernate applies the limit in memory and logs a warning.
- One query with a JOIN
- Chosen per repository method
- Watch out with paging
- Best for detail screens
- default_batch_fetch_size=50
- Lazy loads grouped with IN (...)
- Works for every relation
- Good global default
- select new ...Summary(...)
- Only needed columns
- No entity tracking cost
- Best for lists and reports
Learn it in 6 short steps
About 1h 40m each. Track them with a timer in your plan.
- 1Map entities with @Entity and @Id~1h 40m
- 2Define one-to-many and many-to-many relations~1h 40m
- 3Write repository and derived queries~1h 40m
- 4Use JPQL and native queries~1h 40m
- 5Compare lazy and eager loading~1h 40m
- 6Fix N+1 queries with fetch joins~1h 40m
Key points
- Mark classes with @Entity and the key with @Id; relations use @OneToMany and @ManyToOne.
- Collections are lazy by default, loaded only when first accessed.
- N+1 queries happen when looping over lazy relations; fix with join fetch or @EntityGraph.
- Turn on SQL logging in development to see the queries Hibernate actually runs.
Key terms
Tap a card to flip it. 0/6 known
Examples
@Entity
class Author {
@Id @GeneratedValue Long id;
String name;
@OneToMany(mappedBy = "author") List<Book> books = new ArrayList<>();
}
interface AuthorRepository extends JpaRepository<Author, Long> {
List<Author> findByNameContainingIgnoreCase(String part);
@Query("select distinct a from Author a join fetch a.books")
List<Author> findAllWithBooks(); // one query instead of N+1
}Book has a matching @ManyToOne Author author field.
An order with lines as a parent-child aggregate
An order owns its lines: lines are saved and deleted with the order. Step 1: the OrderLine side holds the foreign key with a lazy @ManyToOne. Step 2: the Order side uses mappedBy, cascade ALL and orphanRemoval, so removing a line from the list deletes its row. Step 3: the addLine helper keeps both sides in sync. Step 4: saving the order inserts the order and all its lines in one transaction.
@Entity
class PurchaseOrder {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderLine> lines = new ArrayList<>();
void addLine(OrderLine line) { lines.add(line); line.order = this; }
void removeLine(OrderLine line) { lines.remove(line); line.order = null; }
}
@Entity
class OrderLine {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false) PurchaseOrder order;
String sku; int quantity;
}Fixing N+1 on an author list page
The authors page shows each author with their book titles and takes 2 seconds. Step 1: turn on SQL logging and see 1 query for authors plus 1 per author for books. Step 2: add a repository method with @EntityGraph so books are fetched in the same query. Step 3: use it in the service. Step 4: reload the page; the log shows a single select with a left join, and the page loads in milliseconds.
# application.yml (development)
# logging.level.org.hibernate.SQL: debug
interface AuthorRepository extends JpaRepository<Author, Long> {
@EntityGraph(attributePaths = "books")
@Query("select a from Author a order by a.name")
List<Author> findAllWithBooks();
}
// Service, inside @Transactional(readOnly = true)
List<AuthorView> authors = repo.findAllWithBooks().stream()
.map(a -> new AuthorView(a.getName(),
a.getBooks().stream().map(Book::getTitle).toList()))
.toList();Quick reference
- Set fetch = FetchType.LAZY on every @ManyToOne and @OneToOne
- Map enums with @Enumerated(EnumType.STRING)
- Managed entities are saved by dirty checking at commit; no save() needed
- logging.level.org.hibernate.SQL=debug shows every SQL statement
- Fix N+1 with join fetch, @EntityGraph, batch fetching or DTO projections
- spring.jpa.open-in-view=false keeps lazy loading out of the web layer
- ddl-auto=validate in real environments; Flyway owns the schema
- select new com.x.Dto(...) in JPQL loads read-only data without entities
Common mistakes
- Switching everything to EAGER to dodge lazy errors, loading far too much.
- Accessing lazy collections outside a transaction (LazyInitializationException).
- Using CascadeType.ALL on many-to-many, deleting shared rows.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a Product entity (id, sku, name, price) and a repository with methods to find by SKU ignoring case and to get the 5 most expensive products.
- Exercise 2medium
Return a list of OrderSummary(id, customerName, total) records for orders above a minimum total, without loading Order entities.
- Exercise 3hard
A page lists authors with the number of books each has. It currently loads every book. Rewrite it as one query that returns counts, including authors with zero books.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between JPA, Hibernate and Spring Data JPA?
- JPA is the specification (annotations and the EntityManager API). Hibernate is the most popular implementation of it. Spring Data JPA sits on top and generates repository implementations for you.
- Should I turn off open-in-view?
- Usually yes. With it on, the default, lazy loading works during JSON rendering, which hides N+1 problems and holds database connections longer. Set spring.jpa.open-in-view=false and load what you need in the service.
- Why does findAll() feel slow on a big table?
- It loads every row into managed entities. Use paging with findAll(Pageable), a narrower query, or a DTO projection.
- When should I use native queries?
- When you need database-specific features such as window functions, JSON operators or upserts that JPQL cannot express. Keep them in the repository and cover them with Testcontainers tests.