[Spring Data Repositories] learning notes -- add a common method for repository, springrepository
If you want to add a method to all repository, it is not appropriate to use the method mentioned in the previous article.
For the original English version, see
Http://docs.spring.io/spring-data/data-mongo/docs/1.5.2.RELEASE/reference/html/repositories.html#repositories.custom-behaviour-for-all-repositories
1. define your own repository and inherit from the basic repository.
public interface MyRepository<T, ID extends Serializable> extends JpaRepository<T,ID> {void sharedCustomMethod(ID id);}
2. Defining the implementation of repository should also be inherited from the basic repository implementation.
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. Create a repository Factory
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. Use the newly created factory
<repositories base-package="com.acme.repository" factory-class="com.acme.MyRepositoryFactoryBean"/>