Member-only story
10 Spring Boot Performance Optimization Techniques That Actually Make a Difference
1. Fix N+1 Queries Before Optimizing Java Code
Consider an API that returns customers along with their orders.
@GetMapping("/customers")
public List<CustomerResponse> getCustomers() {
return customerRepository.findAll()
.stream()
.map(customer -> new CustomerResponse(
customer.getId(),
customer.getName(),
customer.getOrders().size()
))
.toList();
}Free link
Suppose the application retrieves 100 customers. If accessing getOrders() triggers a separate database query for every customer, the application executes:
- 1 query to retrieve customers.
- 100 additional queries to retrieve their orders.
That’s 101 queries for a single API request.
This is the N+1 query problem.
One solution is to fetch the required relationship using a fetch join.
@Query("""
SELECT DISTINCT c
FROM Customer c
LEFT JOIN FETCH c.orders
""")
List<Customer> findAllWithOrders();








