I'm trying to save and load an object containing a @DBRef to another object that happens to be of a child class type and Spring Data MongoDB loads the field as null.
class Person {
@Id
private long id;
@DBRef
private Food food;
}
class Food {
@Id
private long id;
}
class Burger extends Food {}
I'm saving the objects separately:
Burger burger = new Burger();
foodRepository.save(burger);
Person person = new Person();
person.setFood(burger);
personRepository.save(person);
What happens is that the burger object gets saved in the food collection with the _class value of Burger in MongoDB and the $ref in the Person document points to burger and not food.
person collection:
{
"_id" : NumberLong(1),
"food" : {
"$ref" : "burger",
"$id" : NumberLong(2)
},
"_class" : "Person"
}
food collection:
{
"_id" : NumberLong(2),
"_class" : "Burger"
}
If I load the object using findAll() or findById(), the food field is null. But if i use findByFood() with the burger object, the person object is returned. What am I not understanding correctly here?
personRepository.findById(1L).getFood(); // null
personRepository.findByFood(burger); // Person object