Spring Data JPA中CrudRepository和JpaRepository接口的区别是什么?

当我在网上看到这些例子时,我发现它们是可以互换使用的。

它们之间的区别是什么?

为什么要用其中一种而不是另一种呢?


当前回答

简介:

PagingAndSortingRepository扩展了CrudRepository JpaRepository扩展PagingAndSortingRepository

CrudRepository接口为CRUD操作提供了方法,因此它允许您创建、读取、更新和删除记录,而无需定义自己的方法。

PagingAndSortingRepository提供了使用分页和排序检索实体的附加方法。

最后,JpaRepository添加了一些特定于JPA的更多功能。

其他回答

简介:

PagingAndSortingRepository扩展了CrudRepository JpaRepository扩展PagingAndSortingRepository

CrudRepository接口为CRUD操作提供了方法,因此它允许您创建、读取、更新和删除记录,而无需定义自己的方法。

PagingAndSortingRepository提供了使用分页和排序检索实体的附加方法。

最后,JpaRepository添加了一些特定于JPA的更多功能。

spring-data-jpa 3.x的最新更新

从spring-data-jpa 3开始。X与弹簧靴一起使用。6.x和弹簧芯,

结构和层次结构已经修改,看起来更加清晰。

ListCrudRepository扩展了CrudRepository

ListPagingAndSortingRepository扩展了PagingAndSortingRepository

JpaRepository扩展了ListCrudRepository, listpaging和sortingrepository。

所以基本上新引入的ListPagingAndSortingRepository接口,ListCrudRepository现在代表了旧接口的功能,但返回类型为List<T>,而剩余的PagingAndSortingRepository, CrudRepository处理返回类型为Iterable<T>

在新的(3.x)版本中,结构如下:

在过去(3.0之前),许多返回List<T>的声明方法都直接在JpaRepository中声明,但现在这些方法有单独的接口,它们被提取到ListPagingAndSortingRepository, ListCrudRepository中。

(3.x)之前的结构是

我希望从上面的模式中可以清楚地看到,在3中提到的JpaRepository和CrudRepository是如何被修改的。x版本。

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.

下面是CrudRepository和JpaRepository之间的区别:

克鲁德存储库

CrudRepository是一个基础接口,它扩展了Repository接口。 CrudRepository主要提供CRUD (Create, Read, Update, Delete)操作。 saveAll()方法的返回类型为Iterable。 用例—为了执行CRUD操作,定义扩展CrudRepository的存储库。

JpaRepository

JpaRepository扩展了PagingAndSortingRepository,后者扩展了CrudRepository。 JpaRepository提供了CRUD和分页操作,以及其他方法,如flush()、saveAndFlush()和deleteInBatch()等。 saveAll()方法的返回类型为List。 用例-为了执行CRUD和批处理操作,定义存储库extends JpaRepository。

我正在学习Spring Data JPA。它可能会帮助你:

Crud Repository是基本接口,它充当标记接口。

JPA存储库还扩展了PagingAndSorting存储库。 它提供了所有对实现分页有用的方法。Crud Repository没有提供实现分页和排序的方法

你可以参考- 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。