33

In this document (scroll down to the Unidirectional section):

http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-association-collections

it says that a unidirectional one-to-many association with a join table is much preferred to just using a foreign key column in the owned entity. My question is, why is it much preferred?

UrLicht
  • 939
  • 1
  • 14
  • 25
  • see http://stackoverflow.com/questions/2092611/why-is-it-recommended-to-avoid-unidirectional-one-to-many-association-on-a-forei – Adriano Oct 23 '12 at 11:30

2 Answers2

39

Consider the situation where the owned entity type can also be owned by another parent entity type. Do you put foreign key references in the owned table to both parent tables? What if you have three parent types? It just doesn't scale to large designs.

A join-table decouples the join, so that the owned table has no knowledge of the parent table(s), allowing the design to scale elegantly.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    See the difference of internal SQL operations being invoked in join table and foreign key at http://stackoverflow.com/q/18333198/418439 – Lee Chee Kiam Aug 22 '13 at 02:20
11

If the child entity has only ever one parent type, then there is no need for a join table. I've done this with JPA (with a hibernate impl.).

Advantages: One less table. Perhaps better performance. No "what is this table for?" type questions.

Disadvantage: From the OO perspective there is an additional dependency between child and parent introduced. In practice this is probably not such a big deal, since the relationship is private in the child.

e.g. 
parent:
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
@MapKey(name = "name")
private Map children;

child:
@ManyToOne(optional = false)
private Parent parent;
Conor
  • 2,419
  • 3
  • 19
  • 18