README

为所有的repositories添加自定义方法

如果想要给为所有的repository接口增加一个方法,那么之前的方法是不可行的。为了给所有的repository添加自定义的方法,开发者首先需要定义一个中间过渡的接口。

Example 20. An interface declaring custom shared behavior(定义中间接口声明)

  1. @NoRepositoryBean
  2. public interface MyRepository<T, ID extends Serializable>
  3. extends PagingAndSortingRepository<T, ID> {
  4. void sharedCustomMethod(ID id);
  5. }

现在,开发者的其他repository接口需要继承定义的中间接口而不是继承Repository接口。接下来需要为这个中间接口创建实现类。这个实现类是基于Repository中的基类的(不同的持久化存储继承的基类也不相同,这里以Jpa为例),这个类会被当做repository代理的自定义类来执行。 Example 21. Custom repository base class(自定义reposotory基类)

  1. public class MyRepositoryImpl<T, ID extends Serializable>
  2. extends SimpleJpaRepository<T, ID> implements MyRepository<T, ID> {
  3. private final EntityManager entityManager;
  4. public MyRepositoryImpl(JpaEntityInformation entityInformation,EntityManager entityManager) {
  5. super(entityInformation, entityManager);
  6. // Keep the EntityManager around to used from the newly introduced methods.
  7. this.entityManager = entityManager;
  8. }
  9. public void sharedCustomMethod(ID id) {
  10. // implementation goes here
  11. }
  12. }

Spring中命名空间默认会为base-package下所有的接口提供一个实例。但MyRepository只是作为一个中间接口,并不需要创建实例。所以我们可以使用@NoRepositoryBean注解或将其排除在base-package的配置中

最后一步是使用JavaConfig或Xml配置这个自定义的repository基类。

Example 22. Configuring a custom repository base class using JavaConfig(使用JavaConfig配置repository基类)

  1. @Configuration
  2. @EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)
  3. class ApplicationConfiguration { }

也可使用Xml的方式配置。

Example 23. Configuring a custom repository base class using XML(使用xml配置自定义repository基类)

  1. <repositories base-package="com.acme.repository"
  2. repository-base-class="….MyRepositoryImpl" />