# Spring Data JPA: Repositories, Derived Queries and @Query

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

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-data-jpa-repositories-queries
Last updated: 2026-11-28

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

- Spring creates a proxy over SimpleJpaRepository at startup.
- Invalid derived method names fail application startup.
- Slice skips the count query that Page performs.
- @Modifying queries bypass the persistence context; use clearAutomatically.

## Common follow-up questions

- Difference between JpaRepository and CrudRepository?
- How do you implement dynamic search filters?
- What is a projection?

## Interview tips

- Explain that the implementation is a generated proxy, not magic.
- Mention projections and Slice to show performance awareness.

## Concepts covered

Spring Data JPA, JpaRepository, Derived Queries, JPQL

Previous: [ResponseEntity and Correct HTTP Status Codes](https://www.internhack.in/learn/interview/spring-boot-interview/spring-responseentity) · Next: [JPA Relationships and the N+1 Query Problem](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-relationships-n-plus-one) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Lazy vs Eager Fetching and LazyInitializationException](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-lazy-vs-eager-fetching)
- [@Transactional: Propagation, Rollback Rules and Self-Invocation](https://www.internhack.in/learn/interview/spring-boot-interview/spring-transactional-pitfalls)
- [Hibernate First-Level and Second-Level Cache](https://www.internhack.in/learn/interview/spring-boot-interview/spring-hibernate-caching)
- [Spring Security Filter Chain and JWT Authentication Flow](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-filter-chain-jwt)
- [Password Encoding with BCrypt in Spring Security](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-password-encoding)
- [Spring Boot Actuator for Production Monitoring](https://www.internhack.in/learn/interview/spring-boot-interview/spring-boot-actuator)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
