[Spring Data Repositories]学习笔记--为repository添加通用的方法

如果想把一个方法加到所有的repository中,用前一篇提到的方法就不合适了。

英文原版,请看

http://docs.spring.io/spring-data/data-mongo/docs/1.5.2.RELEASE/reference/html/repositories.html#repositories.custom-behaviour-for-all-repositories

 

1. 定义自己的repository,要从基础的repository进行继承。

public interface MyRepository<T, ID extends Serializable> extends JpaRepository<T,ID> {
void sharedCustomMethod(ID id);
}

2. 定义repository的实现,也要从基础的repository实现进行继承。

public class MyRepositoryImpl<T,ID extends Serializable> extends SimpleJpaRepository<T,ID> Implements MyRepository<T,ID> {
private EntityManager entityManager;

public MyRepositoryImpl(Class<T> domainClass, EntityManager entityManager){
super(domainClass,entityManager);

this.entityManager = entityManager;
}

public void sharedCustomMethod(ID id){
//implementation goes here
}
}

3. 创建一个repository工厂

public class MyRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable>
  extends JpaRepositoryFactoryBean<R, T, I> {

  protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {

    return new MyRepositoryFactory(entityManager);
  }

  private static class MyRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {

    private EntityManager entityManager;

    public MyRepositoryFactory(EntityManager entityManager) {
      super(entityManager);

      this.entityManager = entityManager;
    }

    protected Object getTargetRepository(RepositoryMetadata metadata) {

      return new MyRepositoryImpl<T, I>((Class<T>) metadata.getDomainClass(), entityManager);
    }

    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {

      // The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory
      //to check for QueryDslJpaRepository's which is out of scope.
      return MyRepository.class;
    }
  }
}

4. 使用新创建的factory

<repositories base-package="com.acme.repository" factory-class="com.acme.MyRepositoryFactoryBean"/>

 

posted @ 2014-08-05 16:41  lemon_bar  阅读(5789)  评论(0编辑  收藏  举报