How to create a custom repository in Spring Data JPA

In this post, we will see how to create a custom repository in Spring Data JPA? We can create custom repository extending any of these interfaces. Each repository has it’s own benefits and power. You can choose according to your need.

Repository
CrudRepository
PagingAndSortingRepository
JpaRepository
QueryByExampleExecutor

Let’s see the first hierarchy of these repository interfaces.

How to create a custom repository in Spring Data JPA

Create a custom repository extending Repository interface. The Repository interface is a marker interface. It doesn’t have any predefined methods.

package com.netsurfingzone.repository;

import java.io.Serializable;

import org.springframework.data.repository.Repository;

import com.netsurfingzone.entity.Student;

public interface StudentRepository extends Repository<Student, Serializable> {

}

 

 

Create a custom repository extending CrudRepository interface. The CrudRepository interface contains methods to perform CRUD operation. You get benefit to use those methods if you define your repository extending CrudRepository interface.

import java.io.Serializable;

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

import com.netsurfingzone.entity.Student;

@Repository
public interface StudentRepository extends CrudRepository<Student, Serializable> {

}

See more about Repository vs CrudRepository here.

 

Create a custom repository extending PagingAndSortingRepository interface. The PagingAndSortingRepository interface contains methods to perform sorting and Pageable.

package com.netsurfingzone.repository;

import java.io.Serializable;

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

import com.netsurfingzone.entity.Student;

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

}

 

Create a custom repository extending JpaRepository interface. The JpaRepository interface contains methods to perform a batch operation. you can use deleteAllInBacth(), saveAndFlush() methods if you define your repository extending JpaRepository.

package com.netsurfingzone.repository;

import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.netsurfingzone.entity.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {

}

See more about Repository vs CrudRepository here.


That’s all about how to create a custom repository in Spring Data JPA.

You may like.


Other Spring Data JPA and Hibernate tutorials.

 

Spring Data JPA Docs.

Summary – We have seen Difference Difference between Repository and CrudRepository in Spring Data JPA.

We have seen Spring Boot custom repository.