I'm looking for a solution to save an object with a null dbref in mongodb java spring framework. Consider the following example:
@Document
public class A {
@Id
private String id;
@DBRef
private B b;
public A() {
this.b = null;
}
...
}
@Document
public class B {
@Id
private String id;
}
Now if I instantiate A, i.e. A a = new A();
and save this object to mongodb via repository, i.e. aRepo.save(a)
. Then, I have the following exception:
org.springframework.data.mapping.model.MappingException: Cannot create a reference to an object with a NULL id.
Is there a way to save an object with a null dbref?
Thanks for your help!
When object MongoTemplate #save method is called, before object is actually saved it is being converted into DBObject from MongoDB api. CascadingMongoEventListener implemented below provides hook that catches object before its converted and: goes through all its fields to check if there are fields annotated with @DBRef and @CascadeSave at once.
Only using the person id I mean. DBRef means from what I understand a link to another document in MongoDB, so since the Person already exist in the db it should be sufficient to just give it the id and it should link to it or am I wrong? – Keyhan
2. MongoDB Manual Database Reference The first type that we discuss is called the manual reference. In MongoDB, every document must have an id field. Therefore, we can rely on using it and connect documents with it. When using manual references, we store the _id of the referenced document in another document.
This tutorial will continue to explore some of the core features of Spring Data MongoDB – the @DBRef annotation and life-cycle events. 2. @DBRef The mapping framework doesn't support storing parent-child relations and embedded documents within other documents.
You are using @DBREF, so you need to create object B first to DB. You can do so:
B b = new B();
mongoOperations.save(b);
A a = new A();
a.setB(b)
mongoOperations.save(a);
Dbref encapsultes multi collection data fetching in a FOREGIN KEY
kinda-way. If you're using @DBRef
on a field it means that you have this entity already stored, so it must have an @Id
. If you want to just store data in an object without cross-collection reference just remove the @DBRef
annotation.
For example this is how your data looks in mongodb with @DBRef
:
{
"_id" : ObjectId("5bd1e18ee5adfb64cf7edc5c"),
"b" : {
"$ref" : "b",
"$id" : ObjectId("5bd1e1b7e5adfb65f847159d")
},
"_class" : "namespace.A"
}
And this is how it looks without @DBRef
{
"_id" : ObjectId("5bd1e18ee5adfb64cf7edc5c"),
"b" : {
"id" : "someid",
"anotherfield" : "somevalue"
},
"_class" : "namespace.A"
}
Here's how to set a dbref field:
B b = bRepository.findById("someid").get();
A a = new A();
a.setB(b);
aRepository.save(a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With