• [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"/>
  • 相关阅读:
    线程安全与可重入编写方法
    新手MySQL工程师必备命令速查手册
    分布式之数据库和缓存双写一致性方案解析
    在java代码中用xslt处理xml文件
    Java并发编程之并发代码设计
    Java多线程和并发基础
    Java多线程面试大全
    springboot获取URL请求参数的多种方式
    JAVA文件转换为Base64
    Silver Cow Party
  • 原文地址:https://www.cnblogs.com/lemonbar/p/3892631.html
Copyright © 2020-2023  润新知