@Documented @Retention(value=RUNTIME) @Target(value=FIELD) public @interface DocumentReference
DocumentReference allows referencing entities in MongoDB using a flexible schema. While the goal is the
same as when using DBRef, the store representation is different. The reference can be anything, a single
value, an entire Document, basically everything that can be stored in MongoDB. By default, the
mapping layer will use the referenced entities id value for storage and retrieval.
public class Account {
private String id;
private Float total;
}
public class Person {
private String id;
@DocumentReference
private List<Account> accounts;
}
Account account = ...
mongoTemplate.insert(account);
template.update(Person.class)
.matching(where("id").is(...))
.apply(new Update().push("accounts").value(account))
.first();
lookup() allows defining a query filter that is independent from the _id field and in combination
with writing converters offers a flexible way of defining
references between entities.
public class Book {
private ObjectId id;
private String title;
@Field("publisher_ac") @DocumentReference(lookup = "{ 'acronym' : ?#{#target} }") private Publisher publisher;
}
public class Publisher {
private ObjectId id;
private String acronym;
private String name;
@DocumentReference(lazy = true) private List<Book> books;
}
@WritingConverter
public class PublisherReferenceConverter implements Converter<Publisher, DocumentPointer<String>> {
public DocumentPointer<String> convert(Publisher source) {
return () -> source.getAcronym();
}
}
| Modifier and Type | Optional Element and Description |
|---|---|
String |
collection
The collection the referenced entity resides in.
|
String |
db
The database the referenced entity resides in.
|
boolean |
lazy
Controls whether the referenced entity should be loaded lazily.
|
String |
lookup
The single document lookup query.
|
String |
sort
A specific sort.
|
public abstract String db
MongoDatabaseFactory if empty.public abstract String collection
MongoPersistentEntity.getCollection()public abstract String lookup
Collection or Map property the
individual lookups are combined via an $or operator. target points to the source value (or
document) stored at the reference property. Properties of target can be used to define the reference query.public abstract String sort
Copyright © 2011–2022 Pivotal Software, Inc.. All rights reserved.