Map Java classes to MongoDB documents
masterMorphia uses annotations to map Java classes to MongoDB collections.
Requirements for Persistence:
- Classes must be annotated with either
@Entityor@ExternalEntityto be recognized by Morphia. - Top-level entities (those stored as primary documents) must have a field annotated with
@Idto define the_idvalue. - Embedded types (used as properties within other entities) do not require an
@Idfield.
Common Annotations:
@Entity("collection_name"): Marks a class as a top-level entity. If a string is provided, it specifies the collection name; otherwise, Morphia uses the camel-case class name.@Id: Defines the primary key field (e.g.,ObjectId,long).@Indexes: Used to define indexes on the collection.@Index: Defines a specific index and its fields.@Property("custom_name"): Maps a Java field to a different field name in the MongoDB document.@Reference: Indicates the field refers to another Morphia-mapped entity (stored as aDBRef). The referenced entity must be saved or have an ID assigned before referencing it.
Example Mapping:
@Entity("employees")
@Indexes(
@Index(value = "salary", fields = @Field("salary"))
)
class Employee {
@Id
private ObjectId id;
private String name;
@Reference
private Employee manager;
@Reference
private List<Employee> directReports;
@Property("wage")
private Double salary;
}