3.3.1. 接口调优

Typically, your repository interface will extend Repository, CrudRepository or PagingAndSortingRepository. Alternatively, if you do not want to extend Spring Data interfaces, you can also annotate your repository interface with @RepositoryDefinition. Extending CrudRepositoryexposes a complete set of methods to manipulate your entities. If you prefer to be selective about the methods being exposed, simply copy the ones you want to expose from CrudRepository into your domain repository.

通常来说,自定义repository应该继承RepositoryCrudRepository或者 PagingAndSortingRepository。但是如果你不想直接继承Spring Data提供的任何接口,则可以使用@RepositoryDefinition自定义一个接口去继承。继承CrudRepository将暴露完整的操作实体类的方法。如果你更倾向于选择性的提供方法,直接从CrudRepository拷贝一份到你的接口中。

This allows you to define your own abstractions on top of the provided Spring Data Repositories functionality.

这允许定义自己的顶级的 Spring Data Repositories。

Example 7. 选择性暴露CRUD方法
@NoRepositoryBean
interface MyBaseRepository<T, ID extendsSerializable>extendsRepository<T, ID>{
    T findOne(ID id);
    T save(T entity);
}
interface UserRepository extends MyBaseRepository<User,Long>{
    User findByEmailAddress(EmailAddress emailAddress);
}

In this first step you defined a common base interface for all your domain repositories and exposed findOne(…) as well as save(…).These methods will be routed into the base repository implementation of the store of your choice provided by Spring Data ,e.g. in the case if JPA SimpleJpaRepository, because they are matching the method signatures in CrudRepository. So the UserRepository will now be able to save users, and find single ones by id, as well as triggering a query to find Users by their email address.

首先定义了一个自定义的Repositories并且暴露findOne(…)save(…)方法。这些方法能够被提供了Spring Data 实现的类,例如SimpleJpaRepository访问到,因为他们能够匹配到CrudRepository的签名。因此,继承MyBaseRepositoryUserRepository后便可以保存User、根据ID查找User,或者是根据email查找User。

Note, that the intermediate repository interface is annotated with @NoRepositoryBean. Make sure you add that annotation to all repository interfaces that Spring Data should not create instances for at runtime.

注意:被@NoRepositoryBean标注的中间repository在运行是Spring不会为它创建实例,就是无法注入的意思了,这个很好理解---这个Repository不管理任何具体的实例。

results matching ""

    No results matching ""