Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Thursday, March 16, 2023

What is a Spring Data Repository? JpaRepository, CrudRepository, and PagingAndSortingRepository Example

Hello Java developers, if you are wondering what is Spring Data Repository interfaces like JpaRepository, CrudRepository, and PagingAndSortingRepository and how to use them then you have come to the right place. Earlier, I have shared the best Spring Data JPA courses and in this article, I will give you an overview of different Spring Data Repository interfaces and how to use them with step-by-step examples. The Java Persistence API (JPA) is the standard way of persisting java objects into relational databases. 

The central interface in the Spring Data repository abstraction is Repository and it takes the domain class to manage as well as the id type of the domain class as type arguments. 

The main reason why using the interface is that it acts primarily as a marker interface to capture the types of work with and to help you to discover interfaces that extend this one. 


Spring Data Repository interface Examples

There are different kinds of Spring Data repository interfaces and their functionality. In this tutorial, we are going to discuss,

  • CrudRepository
  • PagingAndSortingRepository
  • JpaRepository

Every repository which is mentioned above extends the generic Repository interface and they each are responsible for different functionality.

Spring Data Hierarchy defines the Repository (marker interface) as the top-level interface.

1. Crud Repository Example

CrudRepository is a Spring Data interface for generic CRUD operations on a repository of a specific type. It provides several methods out of the box for interacting with a database. So we will into this using the example given below.

Dependencies need

Add the following spring-data-jpa and h2 database to your pom.xml file in the spring project.




Example application.

So in here, we create the Student bean which is the Spring Data entity. This class will define the data types that will get persisted to the database when we call the save() method.

 @Entity(name = "Student")

public class Student {
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(unique = true)
    private String studentId;
    private String studentName;

So next thing that has to do is create the CrudRepository interface to work with the Student entity.

public interface studentRepository extends CrudRepository<Student, Long> {

When an instance of this repository is instantiated, the underlying logic will automatically be in place for working with the Student Entity class. So after the repository is instantiated, in order to save it to the database we have to use the created object from the Student class.

StudentRepository repo = context.getBean(StudentRepository.class);
Student student = new Student("IT8985451", "George Oliver");
student =;

This will create a new entry in the database table for StudentEntity.As we did not specify the id value for the student record, the id will auto-increment as we declared it in the Student Entity. The save method will return the saved entity.


Other than the can use the save() method to update an existing entry to our database. Think, if you want to update the above entity that we have already created. Can use the CRUDRepository method findById to get the entity from the database and update its values.

Student student = repo.findByStudentId(StudentId).get();
student.setName("George Charlie");;

So in here, the relevant student’s name will be changed to “George Charlie” with the help of the CRUDRepository method.

Some of the crud functionalities as a brief,

save() – Save an iterable of entities. Here we can pass multiple objects to save them in a batch.

findAll() – get all the entities in the database.

findOne() – get a single entity

count() – count no of entities available in the database.

Delete() – delete an entity based on the passed object.

So these generic examples are providing the query abstractions needed in an application

2. PagingAndSortingRepository Example

extension of CrudRepository to provide additional methods to retrieve entities using the pagination and sorting abstraction. This provides two methods.

Page findAll(Pageable pageable) – returns a Page of entities meeting the paging restriction provided in the Pageable object.

Iterable findAll(Sort sort) – returns all entities sorted by the given options. No paging is applied here.

import org.springframework.stereotype.Repository;

public interface StudentRepository extends 
          PagingAndSortingRepository < Student, Long > {


So using this PagingAndSortingRepository, if you want to set sorted by name with a limited number of records(given no of records), we can achieve it by using the below code snippet.

Sort sort = new Sort(new Sort.Order(Direction.ASC, "studentName")); 
Pageable pageable = new PageRequest(0, 20, sort);

So that’s the explanation about PagingAndSortingRepository in the data repository interface.

3. JpaRepository Example

JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch. Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository.

Main features in JpaRepository,

JpaRepository extends PagingAndSortingRepository that extends CrudRepository.

JpaRepository provides CRUD and pagination operations, along with additional methods like flush(), saveAndFlush(), and deleteInBatch(), etc.

The return type of the saveAll() method is a List.

Use Case - To perform CRUD as well as batch operations, define repository extends JpaRepository.


import org.springframework.stereotype.Repository;
interface ReadOnlyRepository<T> extends Repository<T, Long> {



Methods support in,

findAll() – get a List of all available entities in database

findAll(…) – get a List of all available entities and sort them using the provided condition

save(…) – save an Iterable of entities. Here, we can pass multiple objects to save them in a batch

flush() – flush all pending task to the database

saveAndFlush(…) – save the entity and flush changes immediately

deleteInBatch(…) – delete an Iterable of entities. Here, we can pass multiple objects to delete them in a batch

What is a Spring Data Repository interface? CrudRepository, JpaRepository, and PagingAndSortingRepositoryExample

Difference between CrudRepository, JpaReposistory, PangingAndSortingRepository in Spring Data JPA?

This is one of the popular interview question and it also good way to remember them. As we have seen so far. In Spring Data JPA, there are three commonly used interfaces for working with repositories: CrudRepository, JpaRepository, and PagingAndSortingRepository. While these interfaces are similar in some ways, they have distinct differences in their functionality.

CrudRepository is a simple interface that provides basic CRUD (Create, Read, Update, Delete) operations for an entity. It is the most basic repository interface in Spring Data, and it defines methods such as save(), findById(), and deleteById(). CrudRepository can be extended to create a custom repository for an entity, and the framework will automatically generate the required implementation at runtime.

JpaRepository is a subinterface of CrudRepository and provides additional functionality beyond basic CRUD operations. Specifically, it adds support for JPA-specific operations, such as flushing the persistence context, deleting entities in a batch, and retrieving a single entity by its natural identifier. JpaRepository extends the QueryByExampleExecutor interface, which allows querying by example and provides a rich set of query methods.

PagingAndSortingRepository is another subinterface of CrudRepository that provides methods for pagination and sorting results. It adds two additional methods to the basic CrudRepository: findAll(Pageable pageable) and findAll(Sort sort). These methods allow results to be returned in a specific order and to be split into pages for easier handling of large datasets.

In summary, CrudRepository provides basic CRUD operations for an entity, JpaRepository adds JPA-specific operations, and PagingAndSortingRepository adds methods for pagination and sorting. When deciding which interface to use, developers should consider the specific requirements of their application and choose the interface that provides the necessary functionality.


Now that you know what is Spring Data Repository and various interfaces, its time to revise them. All three interfaces, CrudRepository, JpaRepository, and PagingAndSortingRepository are part of Spring Data JPA and offer pre-defined methods to perform CRUD (Create, Read, Update, Delete) operations on the database.

CrudRepository is the simplest interface among them and provides basic CRUD operations like save(), findById(), delete(), and so on.

JpaRepository extends CrudRepository and provides additional JPA-related methods like flushing the changes to the database, deleting in bulk, and so on.

PagingAndSortingRepository is a further extension that adds support for pagination and sorting of results.

In short, CrudRepository provides basic CRUD operations, JpaRepository provides additional JPA-related methods, and PagingAndSortingRepository adds pagination and sorting support. The choice of which interface to use depends on the specific requirements of your project.

That's all about Spring Data Repository interfaces in Java. This article covered important differences and features of the Spring Data Repository interface. You have also learned about CrudRepository, JpaReposistory, PangingAndSortingRepository, and their differences, and most importantly when to use them and how to use them. So that’s all about the Spring data repository interface. Hope you enjoy it. See you in the next tutorial.

Other Spring Framework articles you may like to explore 

    Thanks for reading this article so far. If you find this Spring Data JPA tutorial and different Repository interface examples like JpaRepository, and CrudRepository useful, please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.


    No comments :

    Post a Comment