Creating the Morphia entities
Morphia uses models called entities that will map to documents in the database. It has a convenient annotation syntax that you can use to define those models and even create indexes.
This application will have two entities—one for the recipes and another for the ingredients.
Let’s start with the ingredients entity, as it’s slightly simpler.
entities/Ingredient.java
You will notice an @Entity annotation above the class definition. This line of code tells Morphia that the following class will be used as an entity. The string passed as a parameter tells Morphia in which collection these documents will go.
In the properties definition of the class, you will list the keys used for this document. Note that there is an @Id annotation to tell Morphia which one of those fields will map to MongoDB’s unique _id field.
The rest of the file is boilerplate, where all the possible constructors, getters, and setters are exposed as public methods. The toString method is also overridden to display the ingredient's name and the value of the healthy property.
Next, you can create the recipe entity, which follows a similar syntax.
entities/Recipe.java
This second is very similar to the first one, apart from the List ingredients property. Thanks to MongoDB’s document model, we can also store information as an embedded array inside a document. This is a powerful feature that sets MongoDB apart from traditional databases.
You will notice that it has an @Reference annotation above it. We will get back to that later on in the advanced operations.
You now have all of your entities created and are ready to connect to the database and perform operations with Morphia. You should still be able to compile and run your application, and the results at this point should be the same as previously.