Friday, October 1, 2021

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

Hello Java developers, if you are wondering what is Spring Data Repository interfaces like JpaRepositoyr, 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

That's all about Spring Data Repository interfaces. This article covered some brief but 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