Every data access class needs standard CRUD operations (create, read, update, delete) plus paging and sorting. Writing these methods manually for every entity creates repetitive code that adds no business value and introduces bugs in transaction management, connection handling, and result mapping.
JpaRepository<T, ID> is a Spring Data JPA interface that provides a full set of CRUD, paging, and sorting operations automatically. By extending it, a repository interface inherits findAll(), findById(), save(), delete(), findAll(Pageable), and more — no implementation code required. Spring Data generates the implementation at runtime.
- Interface hierarchy:
Repository(marker) →CrudRepository(basic CRUD) →PagingAndSortingRepository(pagination) →JpaRepository(JPA-specific: flush, batch) - CrudRepository:
save(S entity),findById(ID id),findAll(),count(),deleteById(ID id),existsById(ID id) - PagingAndSortingRepository:
findAll(Pageable)→ returnsPage<T>with total count;findAll(Sort)→ returns sortedList<T> - JpaRepository additions:
findAll()returnsList<T>(vs Iterable in CrudRepository),flush(),saveAndFlush(),deleteInBatch(),getById() - Runtime proxy: Spring Data creates a JDK dynamic proxy implementing the interface, using
SimpleJpaRepositoryas the default implementation - Custom methods: Declare
findBy...methods; Spring Data parses the method name and generates the query
- CrudRepository: Base interface with full CRUD — return types are
Optional<T>for single result - PagingAndSortingRepository: Adds pagination and sorting support
- JpaRepository: Extends both with JPA-specific batch operations and flush control
- Query by Example:
findAll(Example.of(probe))— query by example object - Specification:
JpaSpecificationExecutorfor dynamic criteria queries - @NoRepositoryBean: Marker for intermediate interfaces that shouldn’t be instantiated
- Built from: Spring Data JPA — JpaRepository is the primary repository interface
- Built from: Hibernate ORM Framework — SimpleJpaRepository delegates to EntityManager (Hibernate)
- Related: JPA Query Methods — Derived query methods extend JpaRepository
- Related: JPA Pagination and Sorting — JpaRepository inherits Pageable support
- Contrasts with: JDBC — JDBC requires manual SQL; JpaRepository is declarative
- save() semantics:
save()is both INSERT and UPDATE — Hibernate checks if ID exists; this can cause extra SELECT queries - getById() vs findById():
getById()returns a reference (proxy, lazy);findById()returns Optional (eager loading) - deleteInBatch vs deleteAll:
deleteInBatch()uses one JPQL DELETE query;deleteAll()loads each entity and calls EntityManager.remove() - Transactional behavior: Repository methods are @Transactional(readOnly=true) for reads, @Transactional for writes