核心概念
Spring Data repository 抽象中的核心接口是 Repository
。它将要管理的域类以及域类的标识符类型作为类型参数。此接口主要用作标记接口,用于捕获要使用的类型并帮助您发现扩展此接口的其他接口。
Spring Data 将域类型视为实体,更具体地说是聚合(aggregate)。因此,您将在整个文档中看到“实体(entity)”一词,它可以与“域类型(domain type)”或“聚合(aggregate)”互换使用。 正如您在引言中可能已经注意到的那样,它已经暗示了领域驱动设计的概念。我们按照 DDD 的含义考虑域对象。域对象具有标识符(否则它们将是没有标识的值对象),在处理某些数据访问模式时,我们需要以某种方式引用标识符。在我们讨论 repository 和查询方法时,引用标识符将变得更有意义。 |
CrudRepository
和 ListCrudRepository
接口为正在管理的实体类提供了完善的 CRUD 功能。
CrudRepository
接口public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S entity); (1)
Optional<T> findById(ID primaryKey); (2)
Iterable<T> findAll(); (3)
long count(); (4)
void delete(T entity); (5)
boolean existsById(ID primaryKey); (6)
// … more functionality omitted.
}
1 | 保存给定的实体。 |
2 | 返回由给定 ID 标识的实体。 |
3 | 返回所有实体。 |
4 | 返回实体数量。 |
5 | 删除给定的实体。 |
6 | 指示具有给定 ID 的实体是否存在。 |
此接口中声明的方法通常被称为 CRUD 方法。ListCrudRepository
提供等效的方法,但它们返回 List
,而 CrudRepository
方法返回 Iterable
。
repository 接口包含一些保留方法,例如 如果名为 |
我们还提供了特定于持久化技术的抽象,例如 JpaRepository 或 MongoRepository 。这些接口扩展了 CrudRepository ,除了像 CrudRepository 这样通用且不依赖于持久化技术的接口之外,它们还暴露了底层持久化技术的能力。 |
除了 CrudRepository
之外,还有 PagingAndSortingRepository
和 ListPagingAndSortingRepository
,它们增加了额外的方法以方便对实体进行分页访问
PagingAndSortingRepository
接口public interface PagingAndSortingRepository<T, ID> {
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}
扩展接口需要由实际的存储模块支持。虽然本文档解释了通用方案,但请确保您的存储模块支持您要使用的接口。 |
要以每页 20 个条目访问 User
的第二页,您可以执行类似以下操作
PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(PageRequest.of(1, 20));
ListPagingAndSortingRepository
提供等效的方法,但返回 List
,而 PagingAndSortingRepository
方法返回 Iterable
。
除了查询方法之外,还提供针对 count 和 delete 查询的查询派生功能。以下列表显示了派生的 count 查询的接口定义
interface UserRepository extends CrudRepository<User, Long> {
long countByLastname(String lastname);
}
以下列表显示了派生的 delete 查询的接口定义
interface UserRepository extends CrudRepository<User, Long> {
long deleteByLastname(String lastname);
List<User> removeByLastname(String lastname);
}