🗄️⚠️ SPRING DATA findAll(): CONVENIENT, BUT NOT ALWAYS SAFE Inspired by Java Champion Vlad Mihalcea.
🗄️⚠️ SPRING DATA findAll(): CONVENIENT, BUT NOT ALWAYS SAFE Inspired by Java Champion Vlad Mihalcea.
Spring Data makes repository creation incredibly easy:
interface PostRepository extends JpaRepository { }
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
postRepository.findAll().stream() .filter(this::matchesBusinessRule) .toList();
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
@Query(""" select p.title from Post p join p.tags t where t.name in :tags """) List<String> findTitlesByTags(List<String> tags);
Only the required data crosses the network. A projection also avoids loading complete entities when only titles are needed.
🔸 DESIGN A SAFER REPOSITORY API
interface BaseRepository<T, ID> extends Repository<T, ID> { Optional<T> findById(ID id); long count(); void deleteById(ID id); }
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👇