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.

 

 

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.

See more about Repository vs CrudRepository here.

 

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

 

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.

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.

Top