My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for

ReferenceAnnotation  
Describes how to annotate fields with referenced objects.
Updated Jan 18, 2011 by scotthernandez

Referencing Objects

Mongo references are references from one document (object) to another within the database. Consider the following classes:

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
}

The question here is: How do we annotate the author field in BlogEntry? We could of course use the @Embedded annotation, but that does not make sense here, since we don't want to store the Author with every BlogEntry instance. Instead we want multiple blog entries to reference a single Author document in Mongo.

For this case we use the @Reference annotation:

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
}

One very important thing to mention when working with references: The referenced object must have been saved in Mongo before saving the object referencing it.

This makes sense, really. In terms of the example above, it means that you must already have an Author in the database before you can create a BlogEntry.

By default, Morphia uses the field name as the value name in Mongo. This can be overridden by specifying a name on the @Reference annotation:

    @Reference("blog_authors")
    private List<Author> authors;
Comment by project member scotthernandez, Aug 25, 2011

Please post question/errors to the user group: http://groups.google.com/group/morphia


Sign in to add a comment
Powered by Google Project Hosting