如果我将该列提升为主键(即标识关系),会发生什么?由于该列现在是主键,我必须使用@id对其进行标记。这种增强的派生标识符支持实际上是
JPA 2.0中的新内容的一部分(请参见JPA 2.0规范中的2.4.1节“对应于派生标识符的主键”)。JPA 1.0不允许在OneToOne或ManyToOne上使用Id。使用JPA 1.0,您必须使用PrimaryKeyJoinColumn,并为外键列定义Basic Id映射。
现在的问题是:@Id + @JoinColumn和@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 the JOINED
mapping strategy to the primary table
of its superclass; it is used within a
SecondaryTable
annotation to join a
secondary table to a primary table;
and it may be used in a OneToOne
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.
参见
这个来源
http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state 表示使用 @ManyToOne 和 @Id 在 JPA 1.x 中是可行的。那么现在谁是正确的呢?
作者使用一个预发布的
JPA 2.0 兼容版本的 EclipseLink(文章发表时的版本为
2.0.0-M7)来撰写一篇关于 JPA 1.0 的文章。这篇文章是具有误导性的,因为作者使用了 JPA 1.0 中
不存在的内容。
记录一下,在EclipseLink 1.1中增加了对OneToOne
和ManyToOne
上的Id
的支持(请参阅来自EclipseLink comitter和Java Persistence wiki书籍的主要贡献者James Sutherland的此消息)。但是我要强调,这不是JPA 1.0的一部分。