Spring Data JPA Repositories

Harry · 11 Sep 2026 · 11 views

Spring Data JPA Repositories

Spring Data JPA turns repository interfaces into working persistence layers. The framework generates implementations at runtime, so you never write the boilerplate CRUD code that used to occupy every service layer. You define an interface, extend a base interface, and get everything for free.

The base interfaces

Repository is a marker interface, CrudRepository adds save, findById, findAll, and delete, JpaRepository adds JPA-specific methods like flush and batching, and PagingAndSortingRepository brings pagination. Most projects should extend JpaRepository.

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
    List<Post> findByPublishedTrueOrderByPublishedAtDesc();
}

What you get for free

Methods such as save, findAll, findById, count, and deleteById work immediately, and every base method is transactional. Query result types let you page through large tables without loading everything at once.

Customizing behavior

Add methods with derived names or @Query, and override base methods with annotations when the default strategy is wrong. Pass a Pageable on any query method and the return type becomes Page or Slice, bringing pagination and metadata for free.

Transactions belong on services

Repository methods are fine-grained transactions. Put @Transactional on service methods that span several repository calls, so a multi-step operation commits or rolls back as one unit.

Key Points

  • Extend JpaRepository to inherit CRUD, paging, and JPA helpers.
  • Spring Data generates implementations from the interface.
  • Derived methods and @Query cover custom logic.
  • Return Page with a Pageable parameter for paged lists.
  • Orchestrate multi-step writes with service-level transactions.
Share this post:

Comments (0)

Please login or register to comment.