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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)