Is there a pattern for Spring Data Mongo to support persisting a link to a separate document in separate collection and having it re-hydrate automagically when its pulled back out of the database?
@Document
class Person <-- Saves to the Person Collection
@id
UUID id
String name
Address address
@Document
class Address --
@id
UUID id
String address1
...
Calling save(person)
I'd want the address property in the database to reflect the Address Id, and have the address object persisted to the address collection. When I pull the Person back out, Address would be a fully hydrated (or maybe lazily?) and accessible.
At the time of writing Spring Data MongoDB 3.2 only supports linking documents via DBRefs. Those however follow a fixed structure so that the value representing the link within the target document looks like this
{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }
@DBRef
allows lazy loading via its lazy
attribute. Please have a look at the reference documentation
The upcoming Spring Data MongoDB 3.3 release will extend the support for linking documents to cover the above mentioned use case. Still the linked document needs to be persisted on its own. @DocumentReference
allows to link Address
via the id
property as outlined below.
@Document
class Person {
@Id
String id;
@DocumentReference
Address address;
}
{
"_id" : "p1457",
"name" : "...",
"address" : "a4711"
}
@DocumentReference
will also support lazy loading and can be used to link a collection of documents.
Please find the full documentation here.