Question

In a Spring Data project if I am using multiple types of repositories i.e JPA repository and Mongo repository and if I am extending CrudRepository then how does Spring Data know which store to choose for that repository? It can use JPA or Mongo. Is it based on the annotation @Document or @Entity added on every persisting entity?

Was it helpful?

Solution

The decision which store a proxy created for a Spring Data repository interface is only made due to your configuration setup. Assume you have the following config:

@Configuration
@EnableJpaRepositories("com.acme.foo")
@EnableMongoRepositories("com.acme.foo")
class Config { }

This is going to blow up at some point as the interfaces in package com.acme.foo are both detected by the MongoDB and JPA infrastructure. To resolve this, both the JavaConfig and XML support allows you to define include and exclude filters so that you can either use naming conventions, additional annotations or the like:

@Configuration
@EnableJpaRepositories(basePackages = "com.acme.foo", 
                       includeFilters = @Filter(JpaRepo.class))
@EnableMongoRepositories(base Packages = "com.acme.foo", 
                         includeFilters = @Filter(MongoRepo.class))
class Config { }

In this case, the two annotations @JpaRepo and @MongoRepo (to be created by you) would be used to selectively trigger the detection by annotating the relevant repository interfaces with them.

A real auto-detection is sort of impossible as it's hard to tell which store you're targeting solely from the repository interface declaration and at the point in time when the bean definitions are created we don't even know about any further infrastructure (an EntityManager or the like) yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top