I am trying to create a proper relationship on Hibernate and I have the following relationship between Recipe and Ingredients entities:
I thought that:
- One recipe can have multiple ingredients
- One ingredient can also be part of different recipes
In this situation, I would create many to many relationship.
However, by considering the unit
and amount
fields in the Ingredient
entity, I think the amount of ingredient for a specific recipe may be changed later. In this situation, each ingredient should be belonging to a specific recipe. As a result, I create one to many relationship as shown on the image.
1. Is the approach (one to many) explained above true?
2. I also think that for a Category entity (that describes recipe categories e.g. vegetarian, diabetic, ...), I should use many to many relationship as the category is not identical for a specific recipe and when updating any category, all the related recipes should be affected. Is this true?
CodePudding user response:
If you want to map a many to many relationship, then you need a relationship table.
So your database tables will be
recipe <-> recipe_ingredient <-> ingredient
As you want to have attributes on the relationship amount and unit will then go to the recipe_ingredient table.
This will also result in three classes. Recipe, RecipeIngreident and Ingredient.
CodePudding user response:
The answer to both of your questions is yes. However, you should still consider many-to-many according to @Simon Martinelli's answer in this situation as you will eventually have many duplicate entries and data for Olive Oil
across many different recipes which will only have unique IDs/Amounts/Units. However, this is just a suggestion and you are free to write your code however you wish.