Spring Data JPA: Repositories, Derived Queries and @Query

Difficulty: Intermediate

Question

How does Spring Data JPA work? Explain repository interfaces, derived query methods, and when you would use @Query.

Answer

Writing the same DAO code over and over, save, findById, findAll, delete, is boring and error-prone. Spring Data JPA removes it. You declare an interface, and Spring generates the implementation at startup. That sounds like magic, so let's understand what really happens, because the mechanism is exactly what interviewers probe.

You extend one of the repository interfaces. CrudRepository gives basic create, read, update, delete. PagingAndSortingRepository adds pagination and sorting. JpaRepository extends both and adds JPA-specific operations like flush and saveAllAndFlush. You write interface StudentRepository extends JpaRepository<Student, Long>, the two type parameters being the entity and its id type. At startup Spring creates a dynamic proxy backed by SimpleJpaRepository, the default implementation, and registers it as a bean. Calling save on it delegates to the EntityManager. That proxy is also where transaction handling comes from: the CRUD methods are already transactional.

Derived query methods are the clever part. Spring parses the method name and builds a query. findByEmail becomes a select where email equals the parameter. findByBranchAndYearGreaterThan, findByNameContainingIgnoreCase, findTop5ByOrderByCgpaDesc, existsByEmail, and countByBranch all work. The grammar is: a subject such as find, exists, count or delete, then By, then property expressions joined by And or Or, with keywords such as Between, In, Like, IsNull, OrderBy. If the name refers to a property that does not exist, the application fails at startup, which is a helpful safety net. Derived queries are perfect for simple lookups but become unreadable as names grow, like findByBranchAndYearAndCgpaGreaterThanAndActiveTrueOrderByNameAsc.

For anything more complex, use @Query. It accepts JPQL by default, written against entities and their fields rather than tables, for example select s from Student s where s.branch = :branch and s.cgpa > :min. Use named parameters with @Param. If you need vendor-specific SQL, set nativeQuery = true, at the cost of portability and entity mapping convenience. For queries that modify data, add @Modifying, and remember it needs a transaction and bypasses the persistence context, so cached entities may become stale unless you set clearAutomatically = true.

Other things to mention: projections let you fetch only some columns, using interfaces or records, which cuts payload and memory. Pagination uses a Pageable parameter and returns Page<T> or Slice<T>; Slice avoids the extra count query. Specifications and Querydsl support dynamic filters where criteria are optional. Entity graphs and join fetch fix N+1 problems, which is a separate discussion.

Practical advice: start with derived queries for trivial cases, switch to @Query when the name gets long or joins appear, and always check the generated SQL with spring.jpa.show-sql or better, a proper logger, to make sure you get what you expect. Return Optional for single results so callers handle absence explicitly, and never return entities directly from controllers; map to DTOs.

Code examples

Repository with derived and custom queries

public interface StudentRepository extends JpaRepository<Student, Long> {

    Optional<Student> findByEmail(String email);                       // derived

    List<Student> findByBranchAndCgpaGreaterThanOrderByCgpaDesc(String branch, double min);

    boolean existsByEmail(String email);

    @Query("select s from Student s where lower(s.name) like lower(concat('%', :q, '%'))")
    Page<Student> search(@Param("q") String q, Pageable pageable);     // JPQL + paging

    @Query(value = "select branch, count(*) as total from students group by branch",
           nativeQuery = true)
    List<BranchCount> countPerBranch();                                // native + projection

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query("update Student s set s.active = false where s.lastLogin < :cutoff")
    int deactivateInactive(@Param("cutoff") LocalDate cutoff);
}

public interface BranchCount { String getBranch(); long getTotal(); }

Derived for simple lookups, JPQL for search with paging, native for aggregates, and @Modifying for bulk updates.

Key points

Common follow-up questions

Interview tips

Concepts covered

Spring Data JPA, JpaRepository, Derived Queries, JPQL

More Spring Boot questions