r/SpringBoot • • Oct 06 '26

How-To/Tutorial Your Spring Boot API just ran 11 queries to return 10 users.

Post image

the fix takes 4 lines of code.

Fetching full @Entity graphs for simple read-only endpoints is one of the fastest ways to kill database performance.
Here's what's happening under the hood:
🔴 THE N+1 TRAP
You return a User entity from a REST endpoint. Then:
1️⃣ Hibernate runs 1 SELECT to fetch 10 users
2️⃣ During JSON serialization, the lazy @OneToMany List<Order> gets accessed
3️⃣ That triggers 10 more SQL queries
Total: 11 queries, heavy memory overhead, and a payload full of data nobody asked for.
🟢 THE FIX: INTERFACE PROJECTIONS
Define a lightweight interface with only the getters your client needs:
public interface UserSummary {
Long getId();
String getName();
}
Return List<UserSummary> from your repository, and Spring Data JPA generates a targeted query:
SELECT u.id, u.name FROM users u
⚡ THE RESULT
→ 1 query instead of 11
→ No over-fetching of columns or relations
→ Lower DB CPU usage
→ Faster API responses
💡 RULE OF THUMB
Use @Entity for write/CRUD operations, where the persistence context matters.
Use Interface Projections for read-only APIs and dashboard views.

0 Upvotes

5 comments sorted by

3

u/bobody_biznuz Oct 06 '26

Pretty standard to always return DTOs in your controllers and not the full entity.

1

u/moe-gho Oct 06 '26

Returning DTOs is baseline, but JPA makes ⁠@Entity⁠ so easy that people leak it into controllers anyway. Always project at the query level!

2

u/Torutofu_Raeva Oct 06 '26

also turn off spring.jpa.open-in-view, it's on by default and that's what lets the lazy load quietly fire during serialization instead of blowing up

1

u/rlrutherford Senior Dev Oct 10 '26

Insert/update using Entities.
Query for Records and lazy loading goes away.