What are the Spring Data Repository interfaces?

What are the Spring Data Repository interfaces?

INTRODUCTION

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 Repository interface is the primary interface within the Spring Data repository abstraction. It accepts the domain class to be managed and the id type of the domain class as type arguments.

Different kinds of Spring Data repository interfaces

In this article, we are going to discuss the following types:

  1. CrudRepository

2. JpaRepository

3. PagingAndSortingRepository

A) Crud Repository

CrudRepository is an interface provided by Spring Data for performing generic CRUD operations on a specific type of repository. It includes pre-defined methods that enable easy interaction with a database. To illustrate its usage, we will refer to the following example.

Important dependency:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>3.1.0</version>
</dependency>

Sample Program:

@Entity(name = "student")
public class StudentDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long uniqid;

    @Column(unique = true)
    private String stuID;
    private String stuName;
}

Here, we created Student bean which is the Spring Data Entity.

Now, we will create the CrudRepository interface to work with the StudentDetails entity.

@Repository
public interface stuRepository extends CrudRepository<Student, Long> {
}

When you create a new version of this repository, the necessary rules will be set up automatically to work with the StudentDetails Entity class. Once the repository is created, you need to use the object created from the Student class to save it to the database.

StudentRepository repo = context.getBean(StuRepository.class);
StudentDetails student = new StudentDetails("SLOP2321132", "Saumil");
student = repo.save(student);

This will create a new entry in the database table for Student.

You can use the save() method to update an entry in our database. For example, if you want to update the entity we created earlier.

StudentDetails student = repo.findByStuId(StuId).get();
StudentDetails.setName("Saumil");
repo.save(student);

Here are some basic functions:

  • save(): This function saves a group of items together. You can pass multiple objects at once to save them in one go.

  • findAll(): It retrieves all the items stored in the database.

  • findOne(): This function fetches a single item.

  • count(): It calculates the total number of items in the database.

B) JpaRepository

JpaRepository offers certain JPA-related actions like clearing stored data and deleting multiple records at once. These actions are possible because of the mentioned inheritance.

JpaRepository offers basic operations to create, read, update, and delete data, and it also supports pagination. It has some extra methods like flush(), saveAndFlush(), and deleteInBatch().The saveAll() method returns a List.

If you want to perform CRUD operations and batch operations, you can define a repository that extends JpaRepository.

Sample Program:

public interface StudentInterface extends JpaRepository<Foo, Long> {
    Student findByName(String name);
}

Here are the simplified versions of the sentences:

  1. findAll() — Get a list of all things in the database.

  2. save() — Save a group of things. We can save many objects together.

  3. flush() — Send all unfinished work to the database.

  4. saveAndFlush() — Save something and send the changes to the database right away.

  5. deleteInBatch() — Delete a group of things. We can delete many objects together.

C) PagingAndSortingRepository

The CrudRepository is expanded to offer more ways to get information about entities using pagination and sorting. There are two new methods available for this:

  1. The function “findAll” with the parameter “pageable” returns a collection of items that follow the specified paging settings.

  2. The function “findAll” with the parameter “sort” returns all items sorted according to the specified options. No paging is used in this case.

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends 
          PagingAndSortingRepository < Student, Long > {
}

Conclusion

Differences between CrudRepository, JpaRepository, and PagingAndSortingRepository in Spring Data JPA:

  • CrudRepository is the simplest interface and provides basic CRUD (Create, Read, Update, Delete) operations for an entity.

  • JpaRepository extends CrudRepository and adds additional functionality beyond basic CRUD operations. This includes 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.

  • PagingAndSortingRepository extends JpaRepository and adds methods for pagination and sorting results. This allows results to be returned in a specific order and to be split into pages for easier handling of large datasets.

In this article, we learned about the Spring Data Repository interface in Java. We covered the important differences and features of the interface, as well as the CrudRepository, JpaRepository, and PagingAndSortingRepository interfaces. We also learned when to use each interface and how to use them.

Hope this article has been helpful. Please let me know if you have any questions.