Spring Data JPA and Hibernate
- JPA
- Jakarta Persistence API
Mid-level Always asked 7 min
On this page
The question
What is the N+1 problem, and how do you fix it?
30-second answer
One query loads N parents, then reading a lazy association sends one more query per parent, so 1 + N statements. It stays hidden in tests with little data and hurts in production. Fix it in the query: join fetch or @EntityGraph load everything in one statement, and @BatchSize groups the extra queries. A DTO (data transfer object) projection fetches only what is needed.
Understand it
Count the SQL queries
PredictThree customers are in the database. Customer has a lazy @OneToMany list of orders. This code loads them all and reads each list.
View as text
Two lines of code above a log of SQL statements and a running count. Three customers are in the database. Customer has a lazy @OneToMany list of orders. This code loads them all and reads each list. The learner first predicts the number of statements.
findAll runs one query, for the customers. Their orders are not loaded: each list is an empty placeholder that will query when first touched. The log has one line.
Each size() call touches a lazy list, so each one sends its own query. That is 1 + 3 = 4 statements, and it grows with the data. The log has four lines.
A join fetch reads customers and orders together in one statement. Hibernate 6 removes the duplicate parents for you, so the list still has 3 customers. The log has one line with a join.
FetchType.EAGER does not fix it: findAll still sends one query per customer, and now every use of Customer pays for the orders. The log has four lines again.
@BatchSize loads the lists for several customers in one IN query. That is 2 statements, without changing the query that loads the customers. The log has two lines.
Two lines of code above a log of SQL statements and a running count. Three customers are in the database. Customer has a lazy @OneToMany list of orders. This code loads them all and reads each list. The learner first predicts the number of statements.
findAll runs one query, for the customers. Their orders are not loaded: each list is an empty placeholder that will query when first touched. The log has one line.
Each size() call touches a lazy list, so each one sends its own query. That is 1 + 3 = 4 statements, and it grows with the data. The log has four lines.
A join fetch reads customers and orders together in one statement. Hibernate 6 removes the duplicate parents for you, so the list still has 3 customers. The log has one line with a join.
FetchType.EAGER does not fix it: findAll still sends one query per customer, and now every use of Customer pays for the orders. The log has four lines again.
@BatchSize loads the lists for several customers in one IN query. That is 2 statements, without changing the query that loads the customers. The log has two lines.
Takeaway: Reading a lazy association in a loop costs one query per row. Fetch what you need in the query, with join fetch or @EntityGraph. EAGER does not solve it.
The four states of an entity
Step by stepA plain new object is transient. Hibernate does not know it, it has no id, and no row exists.
View as text
Four boxes for the entity states: transient, managed, detached and removed, with the current one highlighted. A line of code shows the call, a row below shows what the database holds, and a mark names the SQL sent.
A plain new object is transient. Hibernate does not know it, it has no id, and no row exists.
persist makes it managed: the persistence context now tracks it. With a sequence id, it has an id, but no INSERT has been sent yet.
A flush sends the queued SQL, here the INSERT. Flushes happen before a commit and before queries that need the data.
Change a managed object and commit, with no save call. Dirty checking compares it to its snapshot and sends the UPDATE.
Closing the persistence context detaches the object. Changing it now sends nothing, because nobody is tracking it any more.
merge copies a detached object into a managed instance and returns that copy. The original stays detached, so keep using the returned one.
remove schedules a delete. The object is no longer managed, and other transactions still see the row until this one commits.
Four boxes for the entity states: transient, managed, detached and removed, with the current one highlighted. A line of code shows the call, a row below shows what the database holds, and a mark names the SQL sent.
A plain new object is transient. Hibernate does not know it, it has no id, and no row exists.
persist makes it managed: the persistence context now tracks it. With a sequence id, it has an id, but no INSERT has been sent yet.
A flush sends the queued SQL, here the INSERT. Flushes happen before a commit and before queries that need the data.
Change a managed object and commit, with no save call. Dirty checking compares it to its snapshot and sends the UPDATE.
Closing the persistence context detaches the object. Changing it now sends nothing, because nobody is tracking it any more.
merge copies a detached object into a managed instance and returns that copy. The original stays detached, so keep using the returned one.
remove schedules a delete. The object is no longer managed, and other transactions still see the row until this one commits.
Takeaway: Only a managed entity is tracked. Changes to it reach the database with no save call, and changes to a detached one are ignored until you merge.
In code
public interface CustomerRepository extends JpaRepository<Customer, Long> {
// Derived from the method name
Optional<Customer> findByEmail(String email);
List<Customer> findByNameContainingOrderByNameDesc(String part);
// One statement instead of 1 + N
@Query("select c from Customer c join fetch c.orders")
List<Customer> findAllWithOrders();
// The same fix, without writing the join
@EntityGraph(attributePaths = "orders")
@Query("select c from Customer c")
List<Customer> findAllWithGraph();
}@Service
class CustomerService {
private final CustomerRepository customers;
CustomerService(CustomerRepository customers) {
this.customers = customers;
}
@Transactional
void rename(long id, String name) {
Customer customer = customers.findById(id).orElseThrow();
customer.setName(name); // UPDATE is sent at commit
}
}interface OrderSummary {
Long getId();
BigDecimal getTotal();
}
interface OrderRepository extends JpaRepository<Order, Long> {
List<OrderSummary> findByCustomerId(long customerId); // select o.id, o.total: no entity, no lazy fields
}Solve it
The paged orders screen runs 22 queries per page: fix the N+1
GET /orders?page=0&size=20 loads a page of Order entities, and the DTO reads each order’s lazy lines collection.
The SQL log shows the page query, a count query and 20 more, one per order. A join fetch fix made Hibernate warn about paging
in memory.
- Confirm the count. Log SQL with
logging.level.org.hibernate.SQL=DEBUG: the page and its count, then one select of lines per order. That is N+1. - Know why
join fetchhurts here. Fetching a collection multiplies rows, so Hibernate cannot apply the limit in SQL. It loads every order and pages in memory, with warning HHH90003004. - Batch the lazy loads.
hibernate.default_batch_fetch_sizeloads lines for many orders in oneINquery: 3 queries per page instead of 22. - Or use two queries on purpose. Page the ids first, then fetch those orders with their lines by id.
- Check. Count statements in a test with Hibernate statistics, and fail the build if a page needs more than three.
spring:
jpa:
properties:
hibernate:
default_batch_fetch_size: 50 # lines for up to 50 orders in one IN query
generate_statistics: true # lets a test count the statements@Query("select o.id from Order o where o.customerId = :customerId")
Page<Long> findIds(long customerId, Pageable pageable);
@Query("select distinct o from Order o join fetch o.lines where o.id in :ids")
List<Order> findWithLines(Collection<Long> ids);How to answer
- Making the association EAGER does not fix it, and spreads the cost everywhere.
- Detect it by logging SQL, or by asserting the statement count in a test.
- Paginating over a collection
join fetchhappens in memory, and Hibernate warns about it. @BatchSizeneeds no change to the query that loads the parents.
Common mistakes
- Suggesting
FetchType.EAGERas the fix. - Never having looked at the SQL an ORM (object-relational mapping) actually sends.
Follow-up questions
How do Spring Data repository methods work?
You declare an interface extending JpaRepository, and Spring creates the implementation at startup. A method name such as findByEmail is parsed into a query, and a bad property name fails at startup. For anything longer, write JPQL (Jakarta Persistence Query Language) with @Query. JpaRepository already gives save, findById, findAll with paging, and more.
- Derived queries suit one or two conditions; beyond that, names become unreadable.
- A
Pageableparameter adds paging, andPagealso runs a count query. findByIdreturns anOptional;getReferenceByIdreturns a lazy proxy.
interface CustomerRepository extends JpaRepository<Customer, Long> {
Optional<Customer> findByEmail(String email);
@Query("select c from Customer c where c.total > :min")
List<Customer> big(@Param("min") int min);
} What are the states of a JPA entity?
Transient: a new object Hibernate does not know. Managed: tracked by the persistence context, so changes are written at flush. Detached: has an id, but the context was closed, so changes are ignored. Removed: scheduled for deletion at flush. persist makes an object managed, merge copies a detached one into a managed copy, and remove schedules the delete.
- Dirty checking writes a managed entity's changes with no save call.
- The first-level cache returns the same object for one id within a transaction.
- In a Spring transaction, the context lives as long as the transaction.
What is the difference between lazy and eager loading, and which should you use?
Lazy loads an association the first time it is read, through a proxy or a placeholder collection. Eager loads it with the parent, every time. Use lazy for all associations and fetch what each use case needs in its query. @OneToMany is lazy by default, while @ManyToOne and @OneToOne are eager, so set them to lazy.
- EAGER cannot be turned off per query, while lazy can be fetched per query.
- Reading a lazy association with no open session throws
LazyInitializationException. - Boot's
spring.jpa.open-in-viewkeeps a session open for the web request, and is often turned off.
Do you need to call save() after changing an entity inside a transaction?
No. The entity is managed, so at commit Hibernate compares it with its snapshot and sends an UPDATE. A redundant save does no harm. You need it for a new object, which it persists, or for a detached one, which it merges. Then you must use the return value, because merge returns a different object.
- For an entity that is not new,
savecallsmerge, and returns a managed copy. - For a new entity,
savecallspersist, and returns the same object. - Dirty checking only works inside the transaction that loaded the entity.
Customer saved = customers.save(detached);
saved.setName("new"); // tracked
detached.setName("lost"); // not tracked What causes LazyInitializationException, and how do you fix it?
A lazy association was read after the persistence context closed, usually outside the transaction, for example while mapping an entity to JSON in the controller. Fix it by loading what you need while the transaction is open: use join fetch, @EntityGraph, or a DTO built in the service. Do not reach for EAGER.
- Return DTOs from the service, so nothing lazy reaches the web layer.
- Open-in-view hides the error, at the price of queries during serialization.
hibernate.enable_lazy_load_no_transalso hides it, and it is an anti-pattern.
See it in the infographic: The four states of an entity See it in the infographic: Count the SQL queries
Why is paginating with a collection join fetch a problem?
One customer becomes many rows in the join, so the database cannot apply LIMIT to customers. Hibernate loads every row and paginates in memory, with a warning. Page over the ids first, then fetch those parents with their orders, or use @BatchSize. The setting hibernate.query.fail_on_pagination_over_collection_fetch turns the warning into an error.
How can a test catch an N+1 before production?
Turn on hibernate.generate_statistics, read getPrepareStatementCount from Statistics, and assert the number. Use enough rows that N+1 differs from the expected count, and run against the real database. The test fails the day someone adds a lazy read in a loop.
Does a @ManyToOne have the same problem?
Yes, and it is worse: @ManyToOne is EAGER by default, so a query for orders can load each customer with its own select. The persistence context reduces this, since a customer already loaded is not fetched again. Set fetch = LAZY on every @ManyToOne, then fetch deliberately.
Check yourself
Show answers
- 6: Correct. One for the customers, then one per customer for its lazy list.
- 2: Incorrect. That needs batching, through @BatchSize. By default, each list loads alone.
- 1: Incorrect. Nothing in this code asks for a join. That takes join fetch or @EntityGraph.
Show answers
- findAll still sends one query per parent, and every other use now pays for it too.: Correct. EAGER says when to load, not how. findAll runs the same query, then loads each list.
- It becomes one query with a join.: Incorrect. That happens for find by id, not for a JPQL query such as findAll.
- Startup fails.: Incorrect. The mapping is valid. It only changes when the data is loaded.
Show answers
- Nothing: Correct. The object is detached, so nothing tracks it. Saving it would merge the change.
- An UPDATE, right away: Incorrect. Hibernate only writes at flush, and only for managed objects.
- An UPDATE at the next transaction's commit: Incorrect. A later transaction has its own persistence context, which does not know this object.