Introduction
Java Persistence API (JPA) simplifies database interactions by allowing developers to work with Java objects instead of writing SQL for every operation.
With Spring Boot, Spring Data JPA, and Hibernate, we can build data-driven applications quickly using repositories, entity relationships, and transaction management.
However, writing clean JPA code does not automatically guarantee efficient database access.
A simple repository method can unexpectedly execute hundreds of SQL queries. Loading a collection of entities can consume excessive memory. Updating thousands of records one by one can significantly increase database round trips.
In enterprise applications such as banking, payments, insurance, and customer management systems, these issues can directly impact:
- API response time
- Database connection pool utilization
- Transaction throughput
- CPU and memory consumption
- Application scalability
In this article, we will explore three important JPA performance topics:
- N+1 query problem
- Fetch strategies and optimized entity loading
- Batch processing for efficient database operations
Let's understand these concepts with practical Spring Boot and Hibernate examples.
1. Understanding the N+1 Query Problem
The N+1 query problem occurs when an application executes:
- One query to retrieve a collection of parent entities
- N additional queries to retrieve related entities individually
Consider a banking application with customers and their accounts.
Entity relationships
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "customer")
private List<Account> accounts = new ArrayList<>();
}
The Account entity:
@Entity
@Table(name = "accounts")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String accountNumber;
private BigDecimal balance;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
private Customer customer;
}
One customer can have multiple accounts.
The problematic code
List<Customer> customers =
customerRepository.findAll();
for (Customer customer : customers) {
System.out.println(
customer.getAccounts().size()
);
}
At first glance, this looks perfectly reasonable.
But Hibernate may execute the following SQL:
SELECT *
FROM customers;
Then, for every customer:
SELECT *
FROM accounts
WHERE customer_id = ?;
If there are 100 customers, the application may execute:
1 + 100 = 101 SQL queries
If there are 1,000 customers, it may execute 1,001 queries.
This is the N+1 query problem.
Why is N+1 a serious problem?
Each database query introduces overhead:
- Network communication
- SQL parsing and execution
- Database connection usage
- Result-set processing
- Hibernate entity hydration
Even if each query takes only a few milliseconds, hundreds of sequential database calls can significantly increase response time.
In a high-throughput payment or customer service, this can become a major performance bottleneck.
2. Fetch Strategies: LAZY vs EAGER
JPA provides two primary fetch strategies.
LAZY fetching
@OneToMany(fetch = FetchType.LAZY)
private List<Account> accounts;
The related entities are loaded only when accessed.
Advantages:
- Avoids loading unnecessary data
- Reduces initial query size
- Helps control memory consumption
However, accessing lazy relationships inside a loop can cause N+1 queries.
EAGER fetching
@ManyToOne(fetch = FetchType.EAGER)
private Customer customer;
EAGER means the association must be initialized as part of the entity loading process.
Important: EAGER does not guarantee that Hibernate will always use a SQL JOIN.
Hibernate may execute additional queries to satisfy eager loading, depending on the query and mapping.
Therefore, changing LAZY to EAGER is not a reliable solution to the N+1 problem.
Best practice: Prefer LAZY associations and explicitly define the fetch plan required by each use case.
3. Solving N+1 Using JOIN FETCH
One of the most common solutions is JPQL JOIN FETCH.
Instead of loading customers first and accounts separately, we fetch both in a single query.
Repository implementation
@Repository
public interface CustomerRepository
extends JpaRepository<Customer, Long> {
@Query("""
SELECT DISTINCT c
FROM Customer c
LEFT JOIN FETCH c.accounts
""")
List<Customer> findAllWithAccounts();
}
Now execute:
List<Customer> customers =
customerRepository.findAllWithAccounts();
Hibernate can generate SQL similar to:
SELECT
c.id,
c.name,
a.id,
a.account_number,
a.balance,
a.customer_id
FROM customers c
LEFT JOIN accounts a
ON c.id = a.customer_id;
Instead of 101 queries, the application can retrieve the customers and their accounts using one SQL query.
Why LEFT JOIN FETCH?
A customer may not have any accounts.
Using LEFT JOIN ensures that customers without accounts are still included.
Why DISTINCT?
A JOIN produces one row per matching account.
If a customer has three accounts, that customer may appear in three rows in the SQL result.
DISTINCT helps ensure the root Customer entities are returned without duplicate references in the result list.
Important pagination limitation
Be careful when combining collection JOIN FETCH with pagination.
@Query("""
SELECT DISTINCT c
FROM Customer c
LEFT JOIN FETCH c.accounts
""")
Page<Customer> findAllWithAccounts(Pageable pageable);
This can cause inefficient pagination or in-memory pagination because the SQL result contains multiple rows per customer.
For paginated APIs, consider:
- Fetch a page of customer IDs.
- Fetch the required customers and accounts for those IDs.
- Restore the desired ordering if necessary.
For example:
@Query("""
SELECT c.id
FROM Customer c
ORDER BY c.id
""")
Page<Long> findCustomerIds(Pageable pageable);
Then fetch the entities:
@Query("""
SELECT DISTINCT c
FROM Customer c
LEFT JOIN FETCH c.accounts
WHERE c.id IN :ids
""")
List<Customer> findCustomersWithAccounts(
@Param("ids") List<Long> ids);
This approach avoids applying pagination directly to a collection fetch join.
4. Solving N+1 Using @EntityGraph
Another powerful approach is the JPA EntityGraph.
It allows us to specify which relationships should be fetched for a particular repository method without changing the entity's default fetch strategy.
@Repository
public interface CustomerRepository
extends JpaRepository<Customer, Long> {
@EntityGraph(attributePaths = {"accounts"})
List<Customer> findByNameContaining(
String name);
}
The entity mapping remains LAZY:
@OneToMany(mappedBy = "customer",
fetch = FetchType.LAZY)
private List<Account> accounts;
But for this repository method, we request accounts to be loaded as part of the fetch plan.
EntityGraph is particularly useful when:
- Different API endpoints need different relationships
- You want to keep entity mappings clean
- You want to avoid writing multiple JPQL queries
- You need reusable repository methods with specific fetch requirements
Hibernate may choose a JOIN or another query strategy depending on the mapping and provider behavior, so always inspect the generated SQL.
5. Solving N+1 Using Hibernate Batch Fetching
Sometimes JOIN FETCH is not the best option.
For example, an application may need to load customers and their accounts, but joining all collections could produce a very large result set.
Hibernate provides batch fetching to reduce the number of secondary queries.
Configure batch fetching
@OneToMany(mappedBy = "customer")
@BatchSize(size = 50)
private List<Account> accounts;
Or configure it globally:
spring.jpa.properties.hibernate.default_batch_fetch_size=50
When Hibernate initializes lazy associations, it can fetch multiple collections in a single query using an IN clause.
Instead of:
SELECT *
FROM accounts
WHERE customer_id = 1;
SELECT *
FROM accounts
WHERE customer_id = 2;
SELECT *
FROM accounts
WHERE customer_id = 3;
Hibernate may execute:
SELECT *
FROM accounts
WHERE customer_id IN (
1, 2, 3, 4, 5,
...
);
With a batch size of 50, Hibernate can often reduce 100 individual collection queries to approximately two batch queries.
The exact number depends on the number of associations initialized, the persistence context, and Hibernate's batching behavior.
JOIN FETCH vs Batch Fetching
| Feature | JOIN FETCH | Batch Fetching |
|---|---|---|
| Query strategy | SQL JOIN | Multiple IDs in IN clause |
| Database round trips | Often one | Reduced |
| Duplicate root rows | Possible | Avoided |
| Large collections | May produce huge result sets | Often more manageable |
| Pagination | Collection pagination is problematic | Generally more suitable |
| Best use | Small, known fetch graphs | Multiple lazy associations |
There is no universal best strategy. Choose based on the query, relationship cardinality, and expected result size.
6. Batch Processing: INSERT, UPDATE and DELETE
Fetch optimization is only one part of JPA performance.
When an application inserts or updates thousands of records, executing one SQL statement per entity can become expensive.
Hibernate supports JDBC batching to group multiple statements into fewer database round trips.
Enable JDBC batching
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
These properties help Hibernate group compatible INSERT and UPDATE statements.
Example: Batch insert
@Transactional
public void saveAccounts(
List<Account> accounts) {
for (Account account : accounts) {
accountRepository.save(account);
}
}
Although this code calls save() repeatedly, Hibernate may defer SQL execution until flush time.
With JDBC batching enabled, compatible INSERT statements can be sent in batches.
However, batching behavior depends on the identifier strategy.
For example, IDENTITY-based generation often prevents Hibernate from batching INSERT statements because the generated identifier must be obtained immediately.
Sequence-based identifiers are generally more batch-friendly when supported by the database and Hibernate configuration.
Important distinction
JDBC batching reduces database round trips.
It does not automatically reduce the number of SQL statements or eliminate the memory consumed by managed entities.
For large imports, we need a different approach.
7. Processing Large Datasets Using flush() and clear()
Consider importing 100,000 customer accounts.
If every entity remains managed by the persistence context, Hibernate must track a large number of objects.
This can increase memory usage and dirty-checking overhead.
A common solution is to periodically flush and clear the persistence context.
@Transactional
public void importAccounts(
List<Account> accounts) {
int batchSize = 50;
for (int i = 0; i < accounts.size(); i++) {
entityManager.persist(accounts.get(i));
if ((i + 1) % batchSize == 0) {
entityManager.flush();
entityManager.clear();
}
}
entityManager.flush();
entityManager.clear();
}
What does flush() do?
flush() synchronizes pending persistence-context changes with the database.
It does not commit the transaction.
What does clear() do?
clear() detaches all managed entities from the persistence context.
This helps prevent the first-level cache from growing continuously during large batch operations.
Important considerations
- flush() does not commit the transaction.
- clear() detaches all managed entities.
- Accessing detached entities may cause lazy-loading problems.
- Use a transaction strategy appropriate for the business operation.
- For very large imports, consider processing multiple transactions rather than one enormous transaction.
8. Bulk UPDATE and DELETE Using JPQL
For certain operations, loading every entity into memory is unnecessary.
Suppose we need to deactivate 10,000 inactive accounts.
A normal approach might load each account, modify it, and save it individually.
Instead, use a bulk update:
@Modifying
@Query("""
UPDATE Account a
SET a.status = 'INACTIVE'
WHERE a.lastActivityDate < :cutoffDate
""")
int deactivateInactiveAccounts(
@Param("cutoffDate") LocalDate cutoffDate);
Service:
@Transactional
public int deactivateAccounts(
LocalDate cutoffDate) {
return accountRepository
.deactivateInactiveAccounts(cutoffDate);
}
Hibernate can execute this as a single SQL UPDATE statement.
Bulk operation warning
JPQL bulk UPDATE and DELETE operations bypass normal entity-by-entity processing.
They do not automatically synchronize already-managed entities in the persistence context.
If the same entities are already loaded, their in-memory state may become stale.
You may need:
entityManager.flush();
int updated = accountRepository
.deactivateInactiveAccounts(cutoffDate);
entityManager.clear();
Also remember that bulk operations may bypass entity lifecycle callbacks and automatic optimistic-lock handling.
Use them carefully when business rules depend on entity listeners, auditing, or version fields.
9. How to Identify JPA Performance Problems
Never optimize JPA based only on assumptions.
Measure the actual SQL generated by Hibernate.
Enable SQL logging
For local development:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
For more detailed logging:
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.orm.jdbc.bind=TRACE
Avoid enabling bind-parameter TRACE logging in production because it can expose sensitive customer or financial data.
Use Hibernate statistics
spring.jpa.properties.hibernate.generate_statistics=true
Hibernate statistics can help identify:
- Entity fetch counts
- Collection fetch counts
- Query execution counts
- Second-level cache activity
- JDBC batching behavior
In production, use controlled monitoring and SQL observability tools rather than enabling verbose logging indiscriminately.
10. Real-World Fintech Example
Consider a customer dashboard in a banking application.
The dashboard displays:
- Customer profile
- Active accounts
- Account balances
- Recent transactions
A poorly optimized implementation may load customers, then accounts, then transactions individually.
For 100 customers, this could result in hundreds of database queries.
A better architecture uses different fetch plans for different requirements:
| Use case | Recommended approach |
|---|---|
| Customer profile | Direct entity or DTO projection |
| Customer with accounts | JOIN FETCH or EntityGraph |
| Customer with many transactions | Batch fetching or separate paginated query |
| Account summary | DTO projection |
| Large account import | JDBC batching with flush/clear |
| Bulk account status update | JPQL bulk UPDATE |
For read-heavy APIs, DTO projections can be particularly effective because they retrieve only the required columns instead of loading complete entity graphs.
Example:
public record AccountSummary(
Long accountId,
String accountNumber,
BigDecimal balance) {
}
Repository:
@Query("""
SELECT new com.example.dto.AccountSummary(
a.id,
a.accountNumber,
a.balance
)
FROM Account a
WHERE a.customer.id = :customerId
""")
List<AccountSummary> findAccountSummaries(
@Param("customerId") Long customerId);
This avoids unnecessary entity hydration and reduces the amount of data transferred from the database.
11. JPA Performance Best Practices
For production-grade Spring Boot applications, keep these principles in mind:
- Prefer LAZY associations for entity relationships.
- Define explicit fetch plans for each use case.
- Use JOIN FETCH for small, predictable relationship graphs.
- Use EntityGraph when repository methods need different fetch plans.
- Consider batch fetching for multiple lazy associations.
- Avoid collection JOIN FETCH with direct pagination.
- Enable JDBC batching for compatible INSERT and UPDATE operations.
- Use flush() and clear() for large imports.
- Use bulk JPQL operations when entity lifecycle processing is not required.
- Prefer DTO projections for read-heavy APIs.
- Measure generated SQL and query counts.
- Never expose large entity graphs directly through REST APIs without controlling serialization and fetching.
Conclusion
JPA and Hibernate provide powerful abstractions for database access, but performance depends on how we use them.
The N+1 query problem is one of the most common performance issues in ORM-based applications. Fetch strategies, JOIN FETCH, EntityGraph, and batch fetching help control how related entities are loaded.
JDBC batching, persistence-context management, and bulk operations help improve write performance and reduce memory overhead.
As Java backend developers, we should focus not only on writing clean repository methods but also on understanding the SQL generated underneath.
The real goal is not to eliminate every SQL query. It is to minimize unnecessary database round trips while maintaining correctness, scalability, and maintainability.
In enterprise applications, good JPA performance is an important part of building reliable and scalable backend systems.
Author: Ram The Architect (RTA)
Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI
Github: https://github.com/Ramu-fsd/enterprise-banking-microservices
Linkedin: https://www.linkedin.com/in/ramuboya/






Top comments (0)