Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Should I Use @JoinColumn or @JoinTable with JPA?

@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?

like image 753
Sarah Szabo Avatar asked May 17 '15 15:05

Sarah Szabo


People also ask

What is the use of @JoinTable annotation?

Annotation Type JoinTable. Specifies the mapping of associations. It is applied to the owning side of an association. A join table is typically used in the mapping of many-to-many and unidirectional one-to-many associations.

Is @JoinColumn mandatory?

It is not necessary to have @JoinColumn annotation. You can always override it. If you won't provide it in your code then Hibernate will automatically generate one for you i.e. default name for your column.

What is the use of @JoinColumn annotation?

Annotation Type JoinColumn. Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply. (Optional) The SQL fragment that is used when generating the DDL for the column.

In which Entity Relationship Must you use the @JoinTable?

Most often, you will need to use @JoinTable annotation to specify the mapping of a many-to-many table relationship: the name of the link table and. the two Foreign Key columns.


1 Answers

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.

like image 94
Vlad Mihalcea Avatar answered Oct 02 '22 18:10

Vlad Mihalcea