Spring Data JPA Repositories
What are the key trade-offs of Spring Data JPA Repositories? When would you choose it vs alternatives?
Answers use simple, clear English.
Quick interview answer
Pros: Minimal boilerplate; pagination and sorting built-in. Cons: Derived query names explode; N+1 if fetch graphs missing.
Detailed answer
Pros: Minimal boilerplate; pagination and sorting built-in. Cons: Derived query names explode; N+1 if fetch graphs missing. Decision: pick when benefits outweigh operational cost. Core: Interface extending JpaRepository<T,ID> gets CRUD + query methods from method names. @Query for JPQL/native; Pageable for pagination. Real-time example: findByEmailIgnoreCaseAndActiveTrue(String email) generates query at startup. Pros: Minimal boilerplate; pagination and sorting built-in. Cons: Derived query names explode; N+1 if fetch graphs missing. Common mistakes: Long derived method names unreadable; missing @Transactional on service layer writes. Best practices: Use @EntityGraph or JOIN FETCH for associations; DTO projections for reads. Audience level: Fresher.
Full explanation
Interface extending JpaRepository<T,ID> gets CRUD + query methods from method names. @Query for JPQL/native; Pageable for pagination.
Real example & use case
findByEmailIgnoreCaseAndActiveTrue(String email) generates query at startup.
Pros & cons
Pros: Minimal boilerplate; pagination and sorting built-in. Cons: Derived query names explode; N+1 if fetch graphs missing.
Common mistakes
Long derived method names unreadable; missing @Transactional on service layer writes.
Best practices
Use @EntityGraph or JOIN FETCH for associations; DTO projections for reads.
Follow-up questions
- How would you test Spring Data JPA Repositories?
- What metrics prove Spring Data JPA Repositories is healthy in prod?
- How does Spring Data JPA Repositories change at 10× traffic?