自定义Repository

☆樱花仙子☆ 提交于 2020-03-26 12:27:21

  很多情况下除了使用定义好的crud,我们需要为Repository提供一些自定义的实现。这时候使用自定义Repository可以满足要求。

  这里我们新增一个sayHello的方法。

@NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
    void sayHello(String name);
}

  继承JpaRepository是为了继续使用spring自己实现好的那些方法。

  下面完成MyRepository的实现类

@NoRepositoryBean
public class MyRepositoryImpl extends SimpleJpaRepository implements MyRepository {

    private EntityManager entityManager;

    public MyRepositoryImpl(Class domainClass, EntityManager em) {
        super(domainClass, em);
    }


    @Override
    public void sayHello(String name) {
        System.out.println("entityManager:" + entityManager);
        System.out.println("hello," + name);
    }
}

  下面继承JpaRepositoryFactoryBean

public class MyJpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> {

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new MyRepositoryFactory(entityManager);
    }

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


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


        private EntityManager entityManager;

        public MyRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        @Override
        protected Object getTargetRepository(RepositoryInformation information) {
            return new MyRepositoryImpl(information.getDomainType(), entityManager);
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return MyRepository.class;
        }
    }
}

  配置

@SpringBootApplication
@EnableJpaRepositories(repositoryFactoryBeanClass = MyJpaRepositoryFactoryBean.class)
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}