3.1 核心概念

3.1 核心概念

3.1. Core concepts

在Spring Data仓库抽象中的中心接口是Repository。此接口将其id作为参数并使用域类来管理。此接口主要作为一个标记接口来捕获起效的类型并帮助你发现继承此接口的类型。CrudRepository为管理的实体类提供了复杂的CRUD功能。

The central interface in Spring Data repository abstraction is Repository (probably not that much of a surprise). It takes the domain class to manage as well as the id type of the domain class as type arguments. This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one. The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.

例3:CrudRepository接口

Example 3. CrudRepository interface

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {

  <S extends T> S save(S entity);      // 保存指定的实体

  Optional<T> findById(ID primaryKey); // 通过指定id返回实体

  Iterable<T> findAll();               // 返回所有的实体

  long count();                        // 返回所有实体的数量

  void delete(T entity);               // 删除指定实体

  boolean existsById(ID primaryKey);   // 判断指定id的实体是否存在

  // … more functionality omitted.
}

我们也提供了特定技术的持久化抽象,例如JpaRepositoryMongoRepository。这些接口继承了CrudRepository,并暴露了除一般无关持久化技术的持久化特性。

We also provide persistence technology-specific abstractions like e.g. JpaRepository or MongoRepository. Those interfaces extend CrudRepository and expose the capabilities of the underlying persistence technology in addition to the rather generic persistence technology-agnostic interfaces like e.g. CrudRepository.

CrudRepository之上还有一个PagingAndSortingRepository抽象,提供了方便的分页访问实体的一些方法:

On top of the CrudRepository there is a PagingAndSortingRepository abstraction that adds additional methods to ease paginated access to entities:

例4:PagingAndSortingRepository

Example 4. PagingAndSortingRepository

public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {

  Iterable<T> findAll(Sort sort);

  Page<T> findAll(Pageable pageable);
}

按每页数量为20获取User的第二页,可以如下简单实现:

Accessing the second page of User by a page size of 20 you could simply do something like this:

PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(new PageRequest(1, 20));

除了请求方法外,还提供了请求衍生出的计数和删除请求。

In addition to query methods, query derivation for both count and delete queries, is available.

例5:衍生的计数请求

Example 5. Derived Count Query

interface UserRepository extends CrudRepository<User, Long> {

  long countByLastname(String lastname);
}

例6:衍生的删除请求

Example 6. Derived Delete Query

interface UserRepository extends CrudRepository<User, Long> {

  long deleteByLastname(String lastname);

  List<User> removeByLastname(String lastname);
}

翻译部分版权归YahaCode团队所有。仅供学习研究之用,任何组织或个人不得私自以此用于任何形式的商业目的

发表评论