Spring Data JPA Repositories
Implement or sketch code for Spring Data JPA Repositories. Explain the logic, complexity, and pros/cons of this approach.
Answers use simple, clear English.
Quick interview answer
Logic: Interface extending JpaRepository<T,ID> gets CRUD + query methods from method names. @Query for JPQL/native; Pageable for pagination.
Detailed answer
Logic: Interface extending JpaRepository<T,ID> gets CRUD + query methods from method names. @Query for JPQL/native; Pageable for pagination. Complexity notes included in code section when present. Pros: Minimal boilerplate; pagination and sorting built-in. Cons: Derived query names explode; N+1 if fetch graphs missing. 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.
Code example
public interface UserRepo extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
@Query("select u from User u join fetch u.roles where u.id = :id")
Optional<User> findWithRoles(@Param("id") Long id);
Page<User> findByActiveTrue(Pageable pageable);
}Practice code · java (view only · no execution)
public interface UserRepo extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
@Query("select u from User u join fetch u.roles where u.id = :id")
Optional<User> findWithRoles(@Param("id") Long id);
Page<User> findByActiveTrue(Pageable pageable);
}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
Only answered follow-ups are shown — click to open with full answers