Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the @Embedded annotation in Morphia actually do?

When writing documents to Mongodb using Morphia, a structure like this will be written without any problems, and without needing the @Embedded annotation:

@Entity
public class Blog {
    @Id
    private String id;
    private List<Comment> comments;
}

The comments field is happily stored as an array of nested Comment elements (Comment is a plain POJO with no annotations).

However, the Morphia documentation suggests I should be using this:

@Entity
public class Blog {
    @Id
    private String id;
    @Embedded
    private List<Comment> comments;
}

But in my tests using the @Embedded annotation doesn't appear to do anything additional over simply writing the structure without the annotation.

So what does the @Embedded annotation actually do? Does it affect the ability to query, or index, or some other function of storage other than simply writing the data?

like image 281
jimmy_terra Avatar asked Mar 06 '23 15:03

jimmy_terra


2 Answers

Serializable is not generally used with Morphia. @Embedded is a bit of an ambiguous item whose original intent seems to have gotten lost. In fact, in my fork which I'm working on making the official 2.0 of Morphia, I've restricted it such that it only applies at the class level. This tells Morphia to map the type but not fail the mapping on a missing @Id annotation. In that branch if you wish to specify a name other than the field name, you'd simply use @Property as you would for any non-embedded types.

I hope this clarifies it a little bit at least.

like image 138
evanchooly Avatar answered Mar 26 '23 22:03

evanchooly


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.

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;

Even without @Embedded you can still use java class as field type as long as that class implements java.io.Serializable. However that field will be stored in MongoDB in binary format instead of structured data as shown above.

Sources here and here

like image 24
achAmháin Avatar answered Mar 26 '23 21:03

achAmháin