복붙노트

[SPRING] 주어진 도메인 클래스에 대한 스프링 데이터 저장소 인스턴스를 검색하는 방법은 무엇입니까?

SPRING

주어진 도메인 클래스에 대한 스프링 데이터 저장소 인스턴스를 검색하는 방법은 무엇입니까?

어떤 클래스의 모든 스프링 데이터 저장소 목록을 제공 Bar :

@Autowired
private List<Repository> repositories;

위의 목록에서 기존 도메인 클래스 Foo에 대한 저장소를 어떻게 찾을 수 있습니까?

다음이 있다고 가정합니다.

@Entity
public class Foo {
  ...
}

public interface FooRepository extends JpaRepository<Foo, String> {}

해결법

  1. ==============================

    1.Spring Data Commons에는 ListableBeanFactory를 사용하여 정의 된 모든 저장소 빈을 찾는 클래스 저장소가 있으며 도메인 클래스 (.... getRepository (Class type))를 통해 이러한 인스턴스를 얻기 위해 API를 노출합니다.

    Spring Data Commons에는 ListableBeanFactory를 사용하여 정의 된 모든 저장소 빈을 찾는 클래스 저장소가 있으며 도메인 클래스 (.... getRepository (Class type))를 통해 이러한 인스턴스를 얻기 위해 API를 노출합니다.

    이 클래스는주의해서 사용해야합니다. 저장소 인스턴스에 대해 심각한 프록시 생성이 진행되므로 ApplicationContext 생성 중에 Repositories 인스턴스가 가능한 한 늦게 생성되었는지 확인해야합니다. 우선적 인 방법은 ApplicationListener를 구현하고 ContextRefreshedEvent를 수신하여 인스턴스를 만드는 것입니다.

    웹 애플리케이션을 작성하는 경우, Repositories를 사용하는 가장 안전한 방법은 ContextLoaderListener에 의해 생성 된 ApplicationContext의 저장소를 부트 스트랩하고 저장소를 배치하는 것입니다 (자세한 내용은 Spring MVC의 참조 문서를 참조하십시오).

  2. ==============================

    2.

    @Service
    public class GenericRepository {
    
        @Autowired
        private WebApplicationContext appContext;
    
        Repositories repositories = null;
    
        public GenericRepository() {
            repositories = new Repositories(appContext);
        }
    
        public JpaRepository getRepository(AbstractPersistable entity) {
            return (JpaRepository) repositories.getRepositoryFor(entity.getClass());
        }
    
        public Object save(AbstractPersistable entity) {
            return getRepository(entity).save(entity);
        }
    
        public Object findAll(AbstractPersistable entity) {
            return getRepository(entity).findAll();
        }
    
        public void delete(AbstractPersistable entity) {
            getRepository(entity).delete(entity);
        }
    }
    
  3. ==============================

    3.해결책의 열쇠는 Spring의 org.springframework.data.repository.core.support.DefaultRepositoryMetadata는 getDomainType () 메소드를 제공한다.

    해결책의 열쇠는 Spring의 org.springframework.data.repository.core.support.DefaultRepositoryMetadata는 getDomainType () 메소드를 제공한다.

    DefaultRepositoryMetadata는 저장소 인터페이스를 생성자 arg로 필요로합니다. 따라서 기존의 모든 저장소를 반복 할 수 있고 저장소 인터페이스를 검색 할 수 있습니다. 저장소 인터페이스는 저장소 인스턴스에 둘 이상의 인터페이스가 있기 때문에 여전히 까다로운 부분이며 getDomainType ()이 Foo.class와 같은 곳을 찾습니다.

  4. from https://stackoverflow.com/questions/14266089/how-to-retrieve-spring-data-repository-instance-for-given-domain-class by cc-by-sa and MIT license