What's the exact difference between @JoinColumn
and @PrimaryKeyJoinColumn
?
You use @JoinColumn
for columns that are part of a foreign key. A typical column could look like (e.g. in a join table with additional attributes):
@ManyToOne
@JoinColumn(name = "...")
private OtherClass oc;
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
:
@Id
@ManyToOne
@JoinColumn(name = "...")
private OtherClass oc;
Now the question is:
Are @Id
+ @JoinColumn
the same as just @PrimaryKeyJoinColumn
?:
@ManyToOne
@PrimaryKeyJoinColumn(name = "...")
private OtherClass oc;
If not, what's @PrimaryKeyJoinColumn
there for?
This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow
Id
on aOneToOne
orManyToOne
. With JPA 1.0, you'd have to usePrimaryKeyJoinColumn
and also define aBasic
Id
mapping for the foreign key column.You can obtain a similar result but using an
Id
onOneToOne
orManyToOne
is much simpler and is the preferred way to map derived identifiers with JPA 2.0.PrimaryKeyJoinColumn
might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:See also
The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.
For the record, support of
Id
onOneToOne
andManyToOne
has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.I normally differentiate these two via this diagram:
Use
PrimaryKeyJoinColumn
Use
JoinColumn