1115

What is the difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

When I see the examples on the web, I see them there used kind of interchangeably.

  1. What is the difference between them?
  2. Why would you want to use one over the other?
1

9 Answers 9

1519

JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.

Their main functions are:

Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository. So if you don't need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository , use CrudRepository.

1
  • 268
    and returns a List<> instead of Iterable<> in findAll() :-)
    – Hinotori
    Commented Dec 7, 2016 at 18:20
516

Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.

Basics

The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.

The common interfaces

The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:

  • CrudRepository - CRUD methods
  • PagingAndSortingRepository - methods for pagination and sorting (extends CrudRepository)

Store-specific interfaces

The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…) of JpaRepository which is different from delete(…) as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).

We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository.

Custom repository base interfaces

The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:

  1. Depending on a Spring Data repository interface couples your repository interface to the library. I don't think this is a particular issue as you'll probably use abstractions like Page or Pageable in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.
  2. By extending e.g. CrudRepository, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository that doesn't include the save(…) and delete(…) methods of CrudRepository.

The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:

interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }

interface ReadOnlyRepository<T> extends Repository<T, Long> {

  // Al finder methods go here
}

The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long for consistency. The second interface usually has all the find…(…) methods copied from CrudRepository and PagingAndSortingRepository but does not expose the manipulating ones. Read more on that approach in the reference documentation.

Summary - tl;dr

The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.

4
  • This should be the accepted answer: it is not only more complete but also more authoritative because it was written by the "Spring Data Project Lead". Thank you!
    – Pino
    Commented Jan 31, 2023 at 10:39
  • 1
    I am curious as to why saveAndFlush is a method that is only part of something like the JpaRepository? Isn't flushing the persistence context a generic operation? How would we go about having the same functionality without using a technology specific interface - per your recommendation? Commented Mar 30, 2023 at 13:40
  • @Oliver Drotbohm Sorry for the very late question, you say "they expose the underlying persistence technology" but I thought that JPA was just a specification, not an implementation? For example I use Hibernate, but I try to avoid Hibernate-specific code, and I thought using JPA classes instead was better, but maybe there is something I didn't understand?
    – Gaetan L.
    Commented Sep 25, 2023 at 18:41
  • @GaetanL. repository-beans are a concept of spring-data, and spring-data works on top of more than just JPA.
    – julaine
    Commented May 27 at 2:44
125

enter image description here

Summary:

  • PagingAndSortingRepository extends CrudRepository

  • JpaRepository extends PagingAndSortingRepository

The CrudRepository interface provides methods for CRUD operations, so it allows you to create, read, update and delete records without having to define your own methods.

The PagingAndSortingRepository provides additional methods to retrieve entities using pagination and sorting.

Finally the JpaRepository add some more functionality that is specific to JPA.

1
  • What about "extends Repository<>"? Which methods will it have? Same as CrudRepository? Commented Feb 28, 2019 at 17:54
33

I am learning Spring Data JPA. It might help you: enter image description here

2
  • 1
    Hi, nice scheme. Which tool do you use to generate this kind of scheme please? Commented Aug 18, 2021 at 8:54
  • @RozarFabien u asked few years back and I hope u found out how, but i put it here for reference for others too. In the picture of this quesiton I am not sure which tool but, you cna easily do it using Intellij (or any of their IDEs really, depending on the language u use) here their docs jetbrains.com/help/idea/class-diagram.html#analyze_class Commented Jun 8, 2023 at 10:41
29

Below are the differences between CrudRepository and JpaRepository as:

CrudRepository

  1. CrudRepository is a base interface and extends the Repository interface.
  2. CrudRepository mainly provides CRUD (Create, Read, Update, Delete) operations.
  3. Return type of saveAll() method is Iterable.
  4. Use Case - To perform CRUD operations, define repository extending CrudRepository.

JpaRepository

  1. JpaRepository extends PagingAndSortingRepository that extends CrudRepository.
  2. JpaRepository provides CRUD and pagination operations, along with additional methods like flush(), saveAndFlush(), and deleteInBatch(), etc.
  3. Return type of saveAll() method is a List.
  4. Use Case - To perform CRUD as well as batch operations, define repository extends JpaRepository.
20

Recent update, spring-data-jpa 3.x

As of spring-data-jpa 3.x used with spring-boot 3.x and spring-core 6.x,

the structure and the hierarchy has been modified and seems to be more clear.

ListCrudRepository extends CrudRepository

ListPagingAndSortingRepository extends PagingAndSortingRepository

JpaRepository extends both ListCrudRepository, ListPagingAndSortingRepository.

So basically the new introduced interfaces of ListPagingAndSortingRepository, ListCrudRepository now represent the functionalities of the old interfaces but with returned types of List<T> while the remaining PagingAndSortingRepository, CrudRepository handle the return types of Iterable<T>

In the new (3.x) version the structure is the following:

enter image description here

In the past (before 3.0) many of the declared methods which returned List<T> have been directly declared inside the JpaRepository, but now with separate interfaces for those methods they have been extracted into ListPagingAndSortingRepository, ListCrudRepository.

So the structure before (3.x) was

enter image description here

I hope it is clear from the above schemas how the mentioned JpaRepository and CrudRepository have been modified in 3.x version.

In case you plan to migrate spring-data-jpa from 2.x into 3.x (would be necessary if you migrate from spring-boot 2.x to spring-boot 3.x) as illustrated in the above schemas you should expect to have breaking code in cases where you have used the PagingAndSortingRepository in your code, as in the past it was extending from CrudRepository and so your custom repository which extended directly the PagingAndSortingRepository already had access to the methods of CrudRepository. If this is the issue you should fix this by adapting your custom repository to also extend either the ListCrudRepository or the CrudRepository.

12

What is the difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

Spring Data JPA provides both JpaRepository and CrudRepository interfaces to simplify the creation of repositories for data access in JPA-based applications.

CrudRepository is the base interface for entities with basic CRUD (Create, Read, Update, Delete) operations. CrudRepository provides a minimal set of methods like save(), findAll(), findById(), delete(), etc., and can be extended by other custom methods.

It is the code example:

public interface PersonEntityRepository extends CrudRepository<PersonEntity, Long> {

}

JpaRepository interface extends CrudRepository interface. JpaRepository interface provides other additional methods to the basic CRUD operations provided by CrudRepository such as:

  • findAll(Sort sort) - a method which returns all entities sorted by the given criteria.
  • findAll(Pageable pageable) - a method which returns a Page of entities according to the given pagination and sorting criteria.
  • flush() - a method which flushes all pending changes to the database.
  • saveAndFlush(T entity) - a method which saves an entity and immediately flushes changes to the database. It is the code example:
public interface PersonEntityRepository extends JpaRepository<PersonEntity, Long> {

    List<TestEntity> findByName(String name);

    List<Employee> findByAgeGreaterThan(double age);
}

Why would you want to use one over the other?

Choosing between the two depends on the specific needs of your application. I would recommend to use CrudRepository interface for basic CRUD operations, and JpaRepository interface for more advanced functionality such as pagination, sorting, and immediate flushing of changes to the database.

10

All the answers provide sufficient details to the question. However, let me add something more.

Why are we using these Interfaces:

  • They allow Spring to find your repository interfaces and create proxy objects for them.
  • It provides you with methods that allow you to perform some common operations (you can also define your custom method as well). I love this feature because creating a method (and defining query and prepared statements and then execute the query with connection object) to do a simple operation really sucks !

Which interface does what:

  • CrudRepository: provides CRUD functions
  • PagingAndSortingRepository: provides methods to do pagination and sort records
  • JpaRepository: provides JPA related methods such as flushing the persistence context and delete records in a batch

When to use which interface:

According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/

Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.

2

Crud Repository is the base interface and it acts as a marker interface.

JPA repository also extends the PagingAndSorting repository. It provides all the method for which are useful for implementing pagination. Crud Repository doesn't provide methods for implementing pagination and sorting

You can refer - https://www.tutorialspoint.com/difference-between-crudrepository-and-jparepository-in-java#:~:text=Crud%20Repository%20is%20the%20base,acts%20as%20a%20marker%20interface.&text=JPA%20repository%20also%20extends%20the,for%20implementing%20pagination%20and%20sorting.

1
  • 4
    CrudRepository is not a marker interface. baeldung.com/…. Also there are very few (possibly 0) instance of checks for it in the code, so it doesn't act as one either. Commented Sep 28, 2021 at 7:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.