使用Spring Data JPA CrudRepository 和JpaRepository 的好处:
- 继承这些接口,可以使Spring找到自定义的数据库操作接口,并生成代理类,后续可以注入到Spring容器中;
- 可以不写相关的sql操作,由代理类生成
他们存在继承关系:
PagingAndSortingRepository 继承 CrudRepository
JpaRepository 继承 PagingAndSortingRepository
也就是说,
CrudRepository 提供基本的增删改查;
PagingAndSortingRepository 提供分页和排序方法;
JpaRepository 提供JPA需要的方法。
extends PagingAndSortingRepository which in turn extends CrudRepository.
Their main functions are:
- CrudRepository mainly provides CRUD functions.
- PagingAndSortingRepository provides methods to do pagination and sorting records.
- JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.
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
.