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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With