@JoinColumn
和 @PrimaryKeyJoinColumn
的具体区别是什么?
您将 @JoinColumn
用于作为外键一部分的列。典型的列可能如下所示(例如,在具有附加属性的连接表中):
@ManyToOne
@JoinColumn(name = "...")
private OtherClass oc;
如果我也将该列提升为 PK(也称为识别关系),会发生什么情况?由于该列现在是 PK,我必须用 @Id
标记它:
@Id
@ManyToOne
@JoinColumn(name = "...")
private OtherClass oc;
现在的问题是:
@Id
+ @JoinColumn
是否与@PrimaryKeyJoinColumn
相同?:
@ManyToOne
@PrimaryKeyJoinColumn(name = "...")
private OtherClass oc;
如果不是,那 @PrimaryKeyJoinColumn
有什么用?
最佳答案
What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).
这种对派生标识符的增强支持实际上是new stuff in JPA 2.0 的一部分。 (请参阅 JPA 2.0 规范中的 2.4.1 对应于派生身份的主键部分),JPA 1.0 不允许 OneToOne
上的 Id
> 或 ManyToOne
。使用 JPA 1.0,您必须使用 PrimaryKeyJoinColumn
并为外键列定义 Basic
Id
映射。
Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?
您可以获得类似的结果,但在 OneToOne
或 ManyToOne
上使用 Id
会简单得多,并且使用 JPA 2.0 映射派生标识符的首选方式。 PrimaryKeyJoinColumn
可能仍用于 JOINED 继承策略。在 JPA 2.0 规范的相关部分下方:
11.1.40 PrimaryKeyJoinColumn Annotation
The
PrimaryKeyJoinColumn
annotation specifies a primary key column that is used as a foreign key to join to another table.The
PrimaryKeyJoinColumn
annotation is used to join the primary table of an entity subclass in theJOINED
mapping strategy to the primary table of its superclass; it is used within aSecondaryTable
annotation to join a secondary table to a primary table; and it may be used in aOneToOne
mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108]....
If no
PrimaryKeyJoinColumn
annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass....
Example: Customer and ValuedCustomer subclass
@Entity @Table(name="CUST") @Inheritance(strategy=JOINED) @DiscriminatorValue("CUST") public class Customer { ... } @Entity @Table(name="VCUST") @DiscriminatorValue("VCUST") @PrimaryKeyJoinColumn(name="CUST_ID") public class ValuedCustomer extends Customer { ... }
[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over
PrimaryKeyJoinColumn
for the OneToOne mapping case.
另见
This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?
作者正在使用 EclipseLink 的预发布 JPA 2.0 兼容版本(本文发表时版本为 2.0.0-M7)来撰写有关 JPA 1.0(!) 的文章。这篇文章具有误导性,作者使用的东西不是 JPA 1.0 的一部分。
作为记录,在 EclipseLink 1.1 中添加了对 OneToOne
和 ManyToOne
的 Id
支持(参见 this message 中的 James Sutherland , EclipseLink committer 和 Java Persistence wiki book 的主要贡献者)。但让我坚持,这不是 JPA 1.0 的一部分。
关于java - JPA:@JoinColumn 和 @PrimaryKeyJoinColumn 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3417097/