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

EmbeddedAnnotation  
Describes how to annotate fields with embedded objects.
Updated Nov 17, 2010 by scotthernandez

Embedding Objects

We're often dealing with an object structure that does not just have a flat list of fields, but rather a tree of objects. For example, look at the following classes:

public class Hotel {

    private String name;
    private int stars;
    private Address address;

    // ... getters and setters
}

where the Address class looks like this:

public class Address {

    private String street;
    private String city;
    private String postCode;
    private String country;

    // ... getters and setters
}

As a rule of thumb, you should @Embedded for objects that are dependent on the parent object (and therefore have no life outside it), and are not shared between objects. If you need to reference another collection object, look at @Reference, or storing a Key instead.

We just annotate the above classes with @Property and @Embedded:

@Entity
public class Hotel {

    @Id
    private String id;

    private String name;
    private int stars;

    @Embedded
    private Address address;

    // ... getters and setters
}

...

import com.google.code.morphia.annotations.Embedded;

@Embedded
public class Address {

    private String street;
    private String city;
    private String postCode;
    private String country;

    // ... getters and setters
}

As you can see here, classes used solely as embedded objects should not use @Id.

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

    @Embedded("blog_comments")
    private List<Comment> comments;
Comment by killyous...@gmail.com, Nov 2, 2011

How do you change a Address in the Hotel ? for example @Entity public class Hotel {

@Id private String id;
private String name; private int stars;
@Embedded private Hotel Hotel;
// ... getters and setters

}

 If this is the data structure and bottom to modfiy the address ?

Comment by lidde...@gmail.com, Feb 9, 2012

I assume you meant to say

@Entity 
public class Hotel {

@Id private String id;

private String name; private int stars;

@Embedded private Address address;

// ... getters and setters

}

Where Hotel stores an embedded Address (not another Hotel).

You would interact with your objects just like you normally would:

Address address = myHotel.getAddress(); // assumes getAddress() getter in Hotel class
address.setStreet("100 Pleasant Ave"); // assumes setStreet() setter in Address class
address.setCountry("United States"); // assumes setCountry() setter in Address class

Etc, etc. You get the idea. Then, to save your changes:

datastoreReference.save(myHotel);


Sign in to add a comment
Powered by Google Project Hosting