什么时候应该在 JPA 中使用 @JoinColumn 或 @JoinTable?

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

@JoinColumnEntity 另一个 Entity 的外键,而 @JoinTable 将列出 Entity A 和 Entity B. 据我所知,他们似乎都在做类似的事情。我应该什么时候使用其中之一?

假设您有一个实体 A,它与实体 B

@ManyToOne 关联

@JoinColumn 将在使用目标实体 table(例如 B)时定义目标 table 外键(例如 B_ID)。

@Entity
public class A {

    private Long id;

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

}

@JoinTable 将使用单独的 table 来保存 AB 之间的关系。

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

}

这次 AB 都不包含任何外键,因为有一个单独的 table(例如 A_B)来保持 [=12= 之间的关联] 和 B.

@JoinTable 将 table 的 ID 存储到单独的 table 中,而 @JoinColumn 将另一个 table 的 ID 存储在新列中。

@JoinTable:这是默认类型。当您需要更规范化的数据库时使用它。 IE。减少冗余。

@JoinColumn:使用它可以获得更好的性能,因为它不需要加入额外的 table。

一个重要区别@JoinColumn总是depends upon the context它被使用:

  • 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.