How do you use both Spring Data JPA and Spring Data Elasticsearch repositories on the same domain class in a Spring Boot application?

后端 未结 2 1897
执念已碎
执念已碎 2020-12-30 06:14

I\'m trying to use both Spring Data JPA and Spring Data Elasticsearch on the same domain object but it doesn\'t work.

When I tried to run a simple test, I got the fo

相关标签:
2条回答
  • 2020-12-30 06:27

    You can use like this:

    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ElasticsearchCrudRepository.class))
    @EnableElasticsearchRepositories(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ElasticsearchCrudRepository.class))
    public class DataConfiguration {
        ...
    }
    

    Or in SpringBoot:

    @SpringBootApplication
    @EnableJpaRepositories(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ElasticsearchCrudRepository.class))
    @EnableElasticsearchRepositories(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ElasticsearchCrudRepository.class))
    public class MyApplication {
        ...
    }
    
    0 讨论(0)
  • 2020-12-30 06:30

    Repositories in Spring Data are datasource agnostic, meaning that JpaRepository and ElasticsearchRepository both roll up into Repository interface. When this is the case, then auto-configuration of Spring Boot will cause Spring Data JPA to try and configure a bean for each repository in the project that inherits any Spring Data Commons base repository.

    To fix this problem you need to move your JPA repository and Elasticsearch repository to separate packages and make sure to annotate your @SpringBootApplication application class with:

    • @EnableJpaRepositories
    • @EnableElasticsearchRepositories

    Then you need to specify where the repositories are for each enable annotation. This ends up looking like:

    @SpringBootApplication
    @EnableJpaRepositories("com.izeye.throwaway.data")
    @EnableElasticsearchRepositories("com.izeye.throwaway.indexing")
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }
    

    Then your application will be able to disambiguate which repositories are intended for which Spring Data project.

    0 讨论(0)
提交回复
热议问题