简体   繁体   中英

Spring Data Mongo Linked Document Storage

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.

  • Spring Data Mongo 3.1
  • Spring Boot 2.4
  • Groovy 2.5
  • JDK11

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM