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;
How do you change a Address in the Hotel ? for example @Entity public class Hotel {
}
If this is the data structure and bottom to modfiy the address ?
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 classEtc, etc. You get the idea. Then, to save your changes:
datastoreReference.save(myHotel);