Caleb Whittington
Caleb Whittington

Reputation: 107

Hibernate mapping to a self-referential, many-to-many map

In my database I have a Food which has a many-to-many relationship with other ingredient Foods. This relationship is represented as such...

+=============Foods============+    +==========Ingredients===========+
| Id | Name      | Description |    | FoodId | IngredientId | Amount |
+==============================+    +================================+
| 1  | Ice Cream | ........... |    | 1      | 2            | 300    |
+------------------------------+    +--------------------------------+
| 2  | Milk      | ........... |
+------------------------------+

In the domain model, however, the most logical data structure would be a map of Foods and amounts. Ultimately, when I load in "Ice Cream" I need the map to contain all of the ingredient Foods (found through the ingredients table) along with the corresponding value, but I am having trouble figuring out how to do this.

@Entity
@Table(name="Foods")
public class Food {
  @Id 
  @GeneratedValue(strategy = GenerationType.IDENTITY) 
  @Column(name="Id")
  private int id;

  @Column(name="Name")
  private String name;

  @Column(name="Description")
  private String description;

  @ManyToMany ???
  private Map<Food, Integer> ingredients;

Upvotes: 0

Views: 310

Answers (1)

jbx
jbx

Reputation: 22128

I would first create a new entity Ingredient, which has a composite key consisting of both foreign keys, together with the amount integer. You can use Food directly as your field types for both foreign keys.

Then in your Food entity you can add a @OneToMany Set<Ingredient> mapping the id to the Ingredient's foodId. You will then be able to get all the Ingredient entries for one Food easily.

Upvotes: 1

Related Questions