5

I am using Mongo in its simplest avatar possible (in conjunction with Spring Data).

I have two (first class) entities (@Documents) A and B, where A has a reference (@DBRef) of B within it. Everything works fine when creating A and B. However, when reading object A (by Id), the reference B is always null.

I believe DBRefs are eagerly fetched by default (see http://static.springsource.org/spring-data/data-document/docs/current/reference/html/#mapping-usage-references), but the behavior currently is against that. Any ideas why?

Saket
  • 45,521
  • 12
  • 59
  • 79
  • I have the same problem with RC1. Through the shell I see the correct dbref , but when loading the refernce is always null. Did you upgrade the lib? –  Dec 27 '11 at 14:49

2 Answers2

2

You are correct, any DBRefs are eagerly fetched, but they are not eagerly saved (AFAIK). If A has a reference to B, when you save A, Spring Data/MongoDB doesn't automatically save B, you have to.

// Incorrect, upon retrieval a.getB() == null
A a = new A();
a.setB(new B());
repositoryA.save(a);

// Correct (to the best of my knowledge)
B b = repositoryB.save(new B());
A a = new A();
a.setB(b);
repositoryA.save(a);
Ryan Tenney
  • 1,812
  • 3
  • 16
  • 29
  • yes, I seemed to have figured that out. What I am now looking for is a way/pattern to fetch the referenced objects. So, you can fetch 'A' using findOne(a_id), but how do you fetch B? – Saket Nov 11 '11 at 03:40
  • It ought to be there when you fetch A, just as you were expecting. I don't know of any reason (besides the one in my answer) that A should contain a null reference to B. Have you tried using the `mongo` command line client to connect to the server and run a query? Then you can see whether the DBRef to B is present in any objects A. – Ryan Tenney Nov 11 '11 at 04:22
1

Moving over to the Spring Data Mongo M5 build resolved this. So, must be a bug until then.

Saket
  • 45,521
  • 12
  • 59
  • 79