referencing Objects
MONGO references one document (object) to another in the same database. Consider the class:
public class Blogentry {
private String title;
Private Date publishdate;
Private String body;
Private Author Author;
Getters and Setters
} ...
public class Author {
private String username;
Private String fullName;
Private String EmailAddress;
Getters and Setters
}
One of the questions here is: if we note the author attribute in Blogentry. Of course, we can use @embedded annotations, but that makes no sense, because there is no blogentry instance in which to save a author
Object. Instead, we want to refer to a single author document (object) in MONGO in multiple blog instances.
In this case we use @Reference annotations
Import com.google.code.morphia.annotations.Entity;
Import com.google.code.morphia.annotations.Embedded;
Import Com.google.code.morphia.annotations.Id;
Import com.google.code.morphia.annotations.Reference;
Import Com.google.code.morphia.annotations.Property;
@Entity public
class Blogentry {
@Id
private ObjectId Id;
Private String title;
Private Date publishdate;
Private String body;
@Reference
private Author Author;
Getters and Setters
} ...
@Entity public
class Author {
@Id
private ObjectId Id;
Private String username;
Private String fullName;
Private String EmailAddress;
Getters and Setters
}
When using references, it is important to mention that the referenced pair must have been saved to the MongoDB database before being referenced.
This really means. Just like the example above, a author has been saved to the database before you create a Blogentry object.
By default, Morphia uses the property name as the value saved in the database. Of course this can be specified in the @reference annotation.
@Reference ("Blog_authors")
private list<author> authors;
Supplemental: The parameters used by the annotation.
Concreteclass: Specifies the specific entity class.
Ignoremissing: Ignore any references that cannot be resolved.
Lazy: Create a proxy for the reference that will be loaded on the first call (similar to the lazy attribute in hibernate)
Value: Specifies the name of the property stored in the MONGO.
Original connection: Http://code.google.com/p/morphia/wiki/ReferenceAnnotation