Quantcast
Channel: Spring Community Forums - Data
Viewing all articles
Browse latest Browse all 297

Best Practice Request: Repositories with Multiple Datasources

$
0
0
What's the best practice regarding configuring an application to have multiple datasources leveraging the same repositories?

I suspect that my current approach is utterly mangling the project's intentions, so please have a look...


Example:

Code:

public interface FooRepository extends MongoRepository<Foo, String>{}
Now let's say I have a couple of services that use this repository, that I want to wire in automatically...

Code:


public class Foo1Service{
    public Foo1Service(FooRepository fooRepo){}
}

public class Foo2Service{
    public Foo1Service(FooRepository fooRepo){}
}

From what I understand, in order to have two different DataSources, I'd need to create another interface extending my original one.

Code:

public interface FooRepository2 extends FooRepository{}
And then in the ApplicationContext.xml:

Code:


    <mongo:mongo id="fooMongo1" replica-set="..."/>
    <mongo:mongo id="fooMongo2" replica-set="..."/>


    <mongo:db-factory id="fooMongoFactory1" dbname="foo" mongo-ref="fooMongo1"/>
    <bean id="fooMongoTemplate1" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="fooMongoFactory1"/>
    </bean>
    <mongo:repositories base-package="..." mongo-template-ref="fooMongoTemplate1" >
        <repo:include-filter type="regex" expression="FooRepository$"/>
    </mongo:repositories>

    <mongo:db-factory id="fooMongoFactory2" dbname="foo" mongo-ref="fooMongo2"/>
    <bean id="fooMongoTemplate2" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="fooMongoFactory2"/>
    </bean>
    <mongo:repositories base-package="..." mongo-template-ref="fooMongoTemplate2" >
        <repo:include-filter type="regex" expression="FooRepository2"/>
    </mongo:repositories>



QUESTION 1:
This cannot be. Surely there is a way to reuse repositories across multiple data sources?

Let's consider a slightly modified scenario. What if I want to Autowire the repositories?

Code:


public class Foo1Service{
    @Autowired
    public Foo1Service(FooRepository fooRepo){}
}

public class Foo2Service {
    @Autowired
    public Foo1Service(FooRepository2 fooRepo){}
}


QUESTION 2:
In this case, we'll get an exception that Foo1Service's constructor's Autowiring has two potential matches, because Repo2 extends Repo1


Summary:

Please set me straight -- I _know_ I'm doing it wrong, but what's the _right_ way to accomplish what I'm after? As it is, my .xml is a mishmash of include and exclude filters, and I'm slowly working my way toward a point of stability... But it's messy and ugly, and Spring is elegant...

Viewing all articles
Browse latest Browse all 297

Trending Articles