0

I was wondering if spring data for MongoDB could handle multiple databases and perform cross database queries and inserts.

for example if I want to store EntityA in DB dbA and EntityB in dbB and EntityA has a reference to EntityB, will Spring Data generate the correct DBRef pointing to the correct collection and the correct database ?

Will I then be able to query EntityA and then eventually lazy fetch EntityB ?

Morphia lacks this functionality alongside other things, and I was wondering if Spring data had it before making the big dive and ditching Morphia.

1
  • I'd be interested in the answer too, this is a valuable question. However, I think you should try it out on just a Hello World like setup, and report back your findings as an answer... I think it would help future finders of this page a lot! Commented Mar 1, 2013 at 11:01

1 Answer 1

1

The DbRef annotation has a db attribute so that you can define the database the reference will be stored in. So assuming a model like this:

class EntityA {
  @DbRef(db = "dbB") EntityB entityB;
}

class EntityB { … }

interface ARepository extends Repository<EntityA, Long> { … }
interface BRepository extends Repository<EntityB, Long> { … }

you're client code should look something like this:

EntityB b = new EntityB(…);
EntityA a = new EntityA(…);
a.setB(b);

// store A manually first   
aRepository.save(a);
bRepository.save(b);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Oliver. I tried setting the db attribute on the annotation but it seems the $db field of the DBRef is not written in the database. Is this normal ? Does Spring have its own way of fetching back the entity from the second database without the $db field ? Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.