Spring Data makes repository creation incredibly easy:
But this also exposes findAll() by default.
That method is not automatically bad. The danger appears when it becomes the default answer for querying a table whose size can grow dramatically in production.
🔸 TL;DR
▪️ findAll() is convenient, not universally wrong.
▪️ Fetching an entire large table to filter in memory is the real anti-pattern.
▪️ Query only the rows and columns required by the use case.
▪️ Repository APIs should prevent dangerous shortcuts, not encourage them.
🔸 THE ANTI-PATTERN
The application loads every row, creates entities, may trigger additional lazy-loading queries and then discards most of the data.
The database is optimized for filtering. Java should not replace the WHERE clause.
🔸 PUSH FILTERING TO THE DATABASE
Only the required data crosses the network. A projection also avoids loading complete entities when only titles are needed.
🔸 DESIGN A SAFER REPOSITORY API
Expose only operations that make sense by default. Add findAll() explicitly for bounded reference tables where loading every row is an informed decision.
🔸 TAKEAWAYS
▪️ Think about future production volume, not today’s test dataset.
▪️ Watch for N+1 queries caused by lazy associations.
▪️ Prefer derived queries, JPQL, SQL, Specifications or projections.
▪️ Keep findAll() only where “all” is genuinely small and intentional.
A repository interface is an API. Every method it exposes becomes an invitation to use it. 🚀
#Java #SpringData #SpringBoot #JPA #Hibernate #SQL #Performance #SoftwareArchitecture #BackendDevelopment #VladMihalcea
Source article: https://vladmihalcea.com/spring-data-findall-anti-pattern/
Go further with Java certification:
Java👇
Spring👇
SpringBook👇
JavaBook👇