36

@JoinColumn gives an Entity a foreign key to another Entity whereas @JoinTable will list the relationship between all relationships between Entity A and Entity B. As far as I can tell, they both appear to do similar things. When should I use one or the other?

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Sarah Szabo
  • 10,345
  • 9
  • 37
  • 60

3 Answers3

57

Let's say you have an entity A which has a @ManyToOne association ot an entity B

@JoinColumn will define the target table Foreign Key (e.g B_ID) while using the target Entity table (e.g. B).

@Entity
public class A {

    private Long id;

    @ManyToOne
    @JoinColumn(name="B_ID")
    private B b;

}

@JoinTable will use a separate table to hold the relationship between A and B.

@Entity
public class A {

    private Long id;

    @ManyToOne
    @JoinTable(
       name = "A_B", 
       joinColumns = @JoinColumn(name = "B_ID"), 
       inverseJoinColumns = @JoinColumn(name = "A_ID")
    )
    private B b;

}

This time neither A nor B contain any Foreign Key, because there's a separate table (e.g. A_B) to hold the association between A and B.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • so a JoinTable is a N-N relationship ? – julio Jul 05 '17 at 10:23
  • 2
    In database terminology, it's a many-to-many association. In this case, one FK will have a unique constraint to turn it into a one-to-many association with a join table. – Vlad Mihalcea Jul 05 '17 at 10:27
24

@JoinTable stores the id of both the table into a separate table while @JoinColumn stores id of the another table in a new column.

@JoinTable : This is the default type. Use this when you you need a more normalized database. ie. to reduce redundancy.

@JoinColumn : Use this for better performance as it does not need to join extra table.

Rabin Pantha
  • 941
  • 9
  • 19
5

one important difference: @JoinColumn always depends upon the context it is used:

  • If the join is for a OneToOne or ManyToOne mapping using a foreign key mapping strategy, the foreign key column is in the table of the
    source entity or embeddable.
  • If the join is for a unidirectional OneToMany mapping using a foreign key mapping strategy, the foreign key is in the table of the target entity.
  • If the join is for a ManyToMany mapping or for a OneToOne or bidirectional ManyToOne/OneToMany mapping using a join table, the
    foreign key is in a join table.
  • If the join is for an element collection, the foreign key is in a collection table.
mhrsalehi
  • 1,124
  • 1
  • 12
  • 29