spring data jpa 使用自定义repository实现类

  • spring data jpa中使用JpaRepository等接口定义repository时,将默认使用SimpleJpaRepository
  • 可通过自定义实现类,改写或自定义接口方法逻辑:
  1. 创建MyJpaRepository实现类
@Repository
@Transactional(readOnly = true)
public class MyRepositoryImpl<T,ID> extends SimpleJpaRepository<T, ID> {
	public MyRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
    }

    public MyRepositoryImpl(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
    }
    ...
}
  1. 创建MyJpaRepositoryFactoryBean
public class MyJpaRepositoryFactoryBean<R extends Repository<T, ID>, T, ID>
        extends JpaRepositoryFactoryBean<R, T, ID> {

    public MyJpaRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }

    @SuppressWarnings("rawtypes")
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new MyJpaRepositoryFactory(em);
    }

    private static class MyJpaRepositoryFactory<T, ID>
            extends JpaRepositoryFactory {

        private final EntityManager em;

        public MyJpaRepositoryFactory(EntityManager em) {
            super(em);
            this.em = em;
        }

        @SuppressWarnings("unchecked")
        protected Object getTargetRepository(RepositoryMetadata metadata) {
            return new MyRepositoryImpl<T, ID>(
                    (Class<T>) metadata.getDomainType(), em);
        }

        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return MyRepositoryImpl.class;
        }
    }
}
  1. 配置JPA
@Configuration
@EnableJpaRepositories(basePackages = {...},
        repositoryFactoryBeanClass = MyJpaRepositoryFactoryBean.class)
public class JPAConfig {}

你可能感兴趣的:(spring,jpa,spring,data)