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.

ppeterka
  • 20,583
  • 6
  • 63
  • 78
azpublic
  • 1,404
  • 4
  • 20
  • 42
  • 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! – ppeterka Mar 01 '13 at 11:01

1 Answers1

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);
Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
  • 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. – azpublic Mar 04 '13 at 15:53