kseeker
kseeker

Reputation: 11313

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

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?

Upvotes: 1127

Views: 517897

Answers (9)

Zufar Sunagatov
Zufar Sunagatov

Reputation: 1316

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.

Upvotes: 12

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 19173

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.

Upvotes: 26

AnushaSP07
AnushaSP07

Reputation: 401

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.

Upvotes: 2

Ken Chan
Ken Chan

Reputation: 90527

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.

Upvotes: 1532

Anil Nivargi
Anil Nivargi

Reputation: 1727

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.

Upvotes: 29

Rahul Vala
Rahul Vala

Reputation: 715

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.

Upvotes: 10

Evan Knox Thomas
Evan Knox Thomas

Reputation: 590

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

Upvotes: 33

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83151

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.

Upvotes: 518

Joby Wilson Mathews
Joby Wilson Mathews

Reputation: 11136

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.

Upvotes: 125

Related Questions