问题
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?
回答1:
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);
回答2:
Moving over to the Spring Data Mongo M5 build resolved this. So, must be a bug until then.
来源:https://stackoverflow.com/questions/8068807/dbrefs-mongo-document-references-not-fetched-eagerly