在同一应用程序上下文中启用两个 Spring 数据存储库(neo4j 和 h2)

Enabling two Spring Data repositories (neo4j and h2) in the same application context

我似乎无法让 SDN(最新快照)与 Spring Data JPA (H2) 一起很好地发挥作用。我不需要跨两个数据存储的事务支持;相反,我的愿望是简单地为同一 class 中的两个商店使用存储库。例如

public MySpringControlledClass{

   @Autowired
   private MyNeo4jBasedRepository myNeo4jBasedRepository;

   @Autowired
   private MyH2BasedRepository myH2BasedRepoistory;
   ...
}

当我同时启用 neo4j 和 JPA 时,我得到一个形式为

的异常

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myNeo4jBasedRepository': Unsatisfied dependency expressed through method 'setMappingContext' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.data.mapping.context.MappingContext] is defined: expected single matching bean but found 2: neo4jMappingContext,jpaMappingContext

这是预期的,因为我现在有两个映射上下文,一个由 SDN 隐式创建,另一个在我的配置中为 spring 数据 JPA 显式创建。

虽然我在 spring 数据 jpa 中找到了描述如何使用两个不同数据库执行此操作的帖子,但我还没有找到如何使用 SDN 和 spring 数据执行此操作的示例JPA 存储,例如 H2。不同之处似乎在于 SDN 对开发人员隐藏了一些样板逻辑。

任何帮助将不胜感激,因为我花了很多时间尝试各种事情并且 none 到目前为止已经证明是富有成效的。

非常感谢!

所以在你的 myNeo4jBasedRepository 中有一个自动连接的 setMappingContext 方法,它不知道是使用 neo4jMappingContext 还是 jpaMappingContext 因为两者这些 bean 与依赖项具有相同的类型。

我不确定向您公开了多少,但如果可能的话,在您的 MyNeo4jBasedRepository 中重写您的 setMappingContext 方法以采用任何 neo4jMappingContext bean 类型的类型以将其获取到 select这个。

或者将 setMappingContext 方法重写为 super.setMappingContext 并在顶部放置一个限定符 @Qualifier("neo4jMappingContext")

@Autowired
@Qualifier("neo4jMappingContext")
public void setMappingContext(TODO todo)
{
  //super.setMappingContext(todo) Sample implementation as before
}

这将确保 Spring select 正确的依赖关系。

已推送到 Spring Data Neo4j 4.2.0.BUILD-SNAPSHOT 的错误修复,这意味着您不再需要使用 @Qualifier 或定义 MappingContext bean在你的配置中。您只需要通过 transactionManagerRef 属性将相应的 PlatformTransactionManager 和 link 定义到您的 @EnableXXXRepositories

我在这里创建了一个项目来演示如何让两个 Spring 数据项目与 Spring 引导一起工作:https://github.com/mangrish/spring-data-jpa-neo4j-with-boot.