Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ManyToMany(mappedBy = "foo")

Foo has:

@ManyToMany(mappedBy = "foos") private Set<Bar> bars 

and Bar has :

@ManyToMany private Set<Foo> foos 

What difference does the location of mappedBy attribute make to a bi-directional relationship , other than whether table is called foo_bar, or bar_foo; and without the mappedBy attribute I get two join tables, both foo_bar and bar_foo.

like image 365
NimChimpsky Avatar asked Jan 01 '13 15:01

NimChimpsky


People also ask

What is MappedBy in OneToMany?

The mappedBy attribute of the @OneToMany annotation references the post property in the child PostComment entity, and, this way, Hibernate knows that the bidirectional association is controlled by the @ManyToOne side, which is in charge of managing the Foreign Key column value this table relationship is based on.

What MappedBy in many to many?

In the Project class, the mappedBy attribute is used in the @ManyToMany annotation to indicate that the employees collection is mapped by the projects collection of the owner side.

Can many to many be unidirectional?

In a relational database in a many-to-many relationship, a row in table X can have more than one matching row in table Y, a row in table Y can have more than one matching row in table X.


2 Answers

The documentation says:

If the association is bidirectional, one side has to be the owner and one side has to be the inverse end (ie. it will be ignored when updating the relationship values in the association table):

So, the side which has the mappedBy attribute is the inverse side. The side which doesn't have the mappedBy attribute is the owner.

The owner side is the side which Hibernate looks at to know which association exists. So, for example, if you add a Foo in the set of foos of a Bar, a new row will be inserted by Hibernate in the join table. If, on the contrary, you add a Bar to the set of bars of a Foo, nothing will be modified in the database.

like image 85
JB Nizet Avatar answered Sep 18 '22 19:09

JB Nizet


mappedBy tells Hibernate which side of the relationship "owns" the link. In OneToMany or OneToOne, using mappyedBy tells Hibernate that there will be a foreign key in the other table which will be used to store the link.

When it comes to ManyToMany, there is a join table, so neither directly has the link to the other object. However, hibernate still needs to know which is the "owning" side to that is knows how to cascade operations.

like image 20
John Farrelly Avatar answered Sep 18 '22 19:09

John Farrelly