Many-to-Many Relationships With Spring Data JPA
Many-to-Many Relationships With Spring Data JPA
@mauricioperez
@mauricioperez
Many to Many
01
Relationship
How to identify a
02 Many-to-Many
relationship?
Real-life example
Let’s suppose given the scenario that you want
many products are into many orders that
customers do for a particular business.
Key Concept
Let’s think about a scenario: “Okay, so if I order one
specifical product (for example a shampoo) and my
girlfriend tries to buy the same shampoo from her
account to give a gift to her mother and also a cup,
then in her order will be two products, and mine’s
one product.”
Ah! the shampoo belongs to two orders and my
girlfriend’s order contains more than one product.
@mauricioperez
03 why do we need
a third table?
The Situation
The reason why we need to implement a middle
table when dealing with many-to-many data, it’s
because data is going to be fixed on both the two
tables, therefore we can’t go on saving data
randomly on one of them (or both) to save the
data dealing/transaction.
Many-To-Many
04 Relationship
components
Many-To-Many
05 Relationship
components
From the Orders entity.
So let’s say we are in the Orders entity, and we are
going to relate to products table. Now, we need
two annotations here: @ManyToMany and
@JoinTable annotation.
Many-To-Many
06 Relationship
components
Many-To-Many
07 Relationship
components
Many-To-Many
08 Relationship
components
From the Orders entity.
Many-To-Many
09 Relationship
components
From the Products Entity.
This relationship’s side will only hold one
annotation: @ManyToMany.
Many-To-Many
10 Relationship
components
From the Products Entity.
@ManyToMany (
mappedBy = “prods”,
fetch = FetchType.EAGER,
cascade = CascadeType.PERSIST
)
Many-To-Many
11 Relationship
components
From the Products Entity.
The question here is: What the hell does the
mappedBy property means?
Code
Demonstration
12 @mauricioperez
Another example
In courses entity
In instructor entity
Thank you!
@mauricioperez