본문으로 바로가기

 

@JoinColumn vs @PrimaryKeyJoinColumn

 

# 의문점

 

1. @JoinColumn과 @PrimaryKeyJoinColumn의 차이점이 무엇일까

2. @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?

 

# 해결

 

1. @JoinColumn과 @PrimaryKeyJoinColumn의 차이점이 무엇일까

 

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 a OneToOne or ManyToOne. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn and also define a Basic Id mapping for the foreign key column.

 

기존 JPA1.0 에서는 OneToOne or ManyToOne 에 Id 를 사용할 수 없었다.그래서 사용했던 것이 @PrimaryKeyJoinColumn.

하지만, JPA2.0에서는 파생 식별자(derived identifiers)가 생겼음. (JPA2.0명세에서 확인가능)

 

 

 2. @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?

 

You can obtain a similar result but using an Id on OneToOne or ManyToOne 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:

 

@Id + @JoinColumn (JPA2.0 방식)@PrimaryKeyJoinColumn (JPA1.0 방식)

결과적으로는 유사하다고 볼 수 있음.

하지만, 전자의 방식 (JPA2.0의 방식)이 더 명료해서 추천.

후자의 방식 (JPA1.0의 방식) 은 상속관계 매핑 (JOINED inheritance) 에서는 여전히 사용됨.

(아래 명세 참고)

 

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.

 

대충 SecondaryTable 과 PrimaryTable이 Join할 때, @PrimaryKeyJoinColumn을 사용한다는 의미.

아래 사용 예시를 보니까 이해가 갔다.

 

Example: Customer and ValuedCustomer subclass

1
2
3
4
5
6
7
8
9
10
11
@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 { ... }
cs

 


 

# 참고자료

 

https://stackoverflow.com/questions/3417097/jpa-difference-between-joincolumn-and-primarykeyjoincolumn

 

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

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

stackoverflow.com

 

반응형