I found this post where it is discussed if references between documents should be established. I want to annotate my Java
class so that references within JSON
documents are created:
{
"id": "3",
"bs": [
{
"name": "abc"
},
{
"name": "def",
"preconditions": ["abc"]
},
{
"name": "ghi",
"preconditions": ["abc"]
}
]
}
Here the objects of the list preconditions have references to objects of the list bs. Is that possible in MongoDB
? How is it called (I was unable to find any information using the keywords "embedded reference" and "reference within documents".) How would a solution look like with morphia?
EDIT:I know the reference annotation but it seems to refernce to anoter collection and not to a list of objects in the same document. I just want to ensure, that the serialized java objects are deserialized correctly (both attributes should become references to the same object).
EDIT II: To clarify my problem I provide the code which I used for testing:
Class A
@Entity("MyAs")
public class A {
@Id
public String name;
@Embedded
public List<B> bs=new LinkedList<B>();
}
Class B
public class B {
@Id
public String bName;
public List<B> preconditions=new LinkedList<B>();
}
In my main method I do the following:
final Datastore datastore = morphia.createDatastore(new MongoClient(),
"Test");
B b1=new B();
b1.bName="b1";
B b2=new B();
b2.bName="b2";
b1.preconditions.add(b2);
List<B> bs=new LinkedList<B>();
bs.add(b1);
bs.add(b2);
A a1=new A();
a1.name="mya1";
a1.bs=bs;
datastore.save(a1);
A myA=datastore.get(A.class,"mya1");
System.out.println(myA.bs.get(0).preconditions.get(0));
System.out.println(myA.bs.get(0).preconditions.get(0).hashCode()+" --" +myA.bs.get(0).preconditions.get(0).bName);
System.out.println(myA.bs.get(1));
System.out.println(myA.bs.get(1).hashCode() +" --" + myA.bs.get(1).bName);
This leads to the following structure in Mongo DB Compass (obviously, no reference is created):
If the document is deserialized then (with datastore.get), obviously two separate objects are created for b2 (outputs of System.out.println
):
mongotest.B@78b729e6
2025269734 --b2
mongotest.B@6b4a4e18
1800031768 --b2
I want to have a structure where the b2 object in preconditions references to the b2 object in bs!
If I do datastore.get(A.class,"mya1");
I want to have the same structure which I used for the serialization: a single B object which is referenced in the bs list and in the preconditions..