42

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.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • 9
    foo and bar are really a poor choice of words for this. Please consider more concrete examples with relationships that exist in the real world. – haventchecked Aug 25 '15 at 19:57

2 Answers2

53

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • what if i want them to reflect each other, if a bar gets added that should modify db as well ? – NimChimpsky Jan 01 '13 at 15:30
  • @NimChimpsky: In a bidirectional relationship, when you change Foo.bars, then you should be changing Bar.foos correspondingly, so you shouldn't care about what gets saved in the DB when you modify what. The "ownership" concept is only about database organization, and your code should be completely ignorant of it. – Ryan Stewart Jan 01 '13 at 15:40
  • 1
    You have a bidirectional association: when you add a bar to a foo, also add the foo to the bar. – JB Nizet Jan 01 '13 at 15:40
  • 1
    @RyanStewart "when you change Foo.bars, then you should be changing Bar.foos correspondingly, so you shouldn't care about what gets saved in the DB when you modify what." ... to me, this sounds contradictory. – Abdull Jun 29 '14 at 20:45
  • What happens if I don't specify `mappedBy` at all? – Lukas Oct 30 '22 at 12:25
2

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.

John Farrelly
  • 7,289
  • 9
  • 42
  • 52
  • 3
    -1: mappedBy doesn't indicate which table has a foreign key, and it has nothing to do with cascades. – JB Nizet Jan 01 '13 at 15:41