且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您如何在 Spring Boot 应用程序的同一个域类上同时使用 Spring Data JPA 和 Spring Data Elasticsearch 存储库?

更新时间:2021-11-23 00:41:48

Spring Data 中的 Repositories 与数据源无关,这意味着 JpaRepositoryElasticsearchRepository 都汇总到 Repository 界面.在这种情况下,Spring Boot 的自动配置将导致 Spring Data JPA 尝试为项目中继承任何 Spring Data Commons 基础存储库的每个存储库配置一个 bean.

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.

要解决此问题,您需要将 JPA 存储库和 Elasticsearch 存储库移动到单独的包中,并确保使用以下内容注释 @SpringBootApplication 应用程序类:

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);
    }

}

然后您的应用程序将能够消除哪些存储库用于哪个 Spring Data 项目.

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