3.1. 核心概念
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. TheCrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.
Repository接口是Spring Data repository的核心接口。该接口有两个参数,一个是被管理实体类,一个是该类的主键(id type).该接口主要作为标记接口(marker interface)来使用 --- 标记它本身是一个Repository,且你可以使用自定义接口继承它。CrudRepository提供了对实体类(entity class)的CRUD操作。
Example 3. CrudRepository interface
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
<S extends T> S save(S entity); // Saves the given entity.
T findOne(ID primaryKey); // Returns the entity identified by the given id.
Iterable<T> findAll(); // Returns all entities.
Long count(); // Returns the number of entities.
void delete(T entity); // Deletes the given entity.
boolean exists(ID primaryKey); // Indicates whether an entity with the given id exists.
// … more functionality omitted.
}
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.
我们还提供了高级抽象层像是JpaRepository或者MongoRepository。他们都继承自CrudRepository并且提供了更高级的功能。
On top of the CrudRepository there is a PagingAndSortingRepository abstraction that adds additional methods to ease paginated access to entities:
构建于CrudRepository之上的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);
}
Accessing the second page of User by a page size of 20 you could simply do something like this:
查询第二页的User信息只需要传递如下的简单的参数:
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.
另外还支持query以及count、delete的衍生方法。
Example 5. Derived Count Query
public interface UserRepository extends CrudRepository<User, Long>{
Long countByLastname(String lastname);
}
Example 6. Derived Delete Query
public interface UserRepository extends CrudRepository<User, Long> {
Long deleteByLastname(String lastname);
List<User> removeByLastname(String lastname);
}