developer tip

JPA에서 referencedColumnName은 무엇에 사용됩니까?

copycodes 2020. 11. 27. 08:21
반응형

JPA에서 referencedColumnName은 무엇에 사용됩니까?


JPA에는 이 설정 뒤에있는 아이디어 referencedColumnName@JoinColumn, @PrimaryKeyJoinColumn대해 설정할 수 있는 속성 이 있습니다 . 누군가이 설정을 사용할 수있는 좋은 예를 제공 할 수 있습니까?


다른 테이블 의 기본 ID 열로 다른 열을 지정하는 것이 있습니다 . 예를 들어 다음을 고려하십시오.

TableA
  id int identity
  tableb_key varchar


TableB
  id int identity
  key varchar unique

// in class for TableA
@JoinColumn(name="tableb_key", referencedColumnName="key")

"referencedColumnName"속성은 주석을 달고있는 열을 참조하는 테이블의 열 이름입니다. 또는 간단히 말해서 대상 테이블에서 참조되는 열입니다. 다음과 같은 것을 상상해보십시오 : 자동차와 사람. 한 사람이 많은 차를 가질 수 있지만 한 차는 한 사람에게만 속합니다 (죄송합니다. 다른 사람이 내 차를 운전하는 것을 좋아하지 않습니다).

테이블 사람
이름 char (64) 기본 키
age int

테이블 Car
car_registration char (32) 기본 키
car_brand (char 64)
car_model (char64)
owner_name char (64) 외래 키 참조 Person (name)

클래스를 구현하면 다음과 같은 것을 갖게됩니다.

class Person{
   ...
}

class Car{
    ...
    @ManyToOne
    @JoinColumn(columnName="owner_name", referencedColumnName="name")
    private Person owner;
}

도움이 되었기를 바랍니다.


referencedColumnName에 대한 견적 API :

이 외래 키 열에서 참조하는 열의 이름입니다.

기본값 (단일 결합 열이 사용되는 경우에만 적용됨) : 참조 된 테이블의 기본 키 열과 동일한 이름입니다.

Q / A

이것이 어디에 사용됩니까?

참조 된 테이블에 복합 PK가있는 경우 참조 하는 열 이름을 지정해야합니다.


  • name 속성은 연관을 포함하는 열을 가리 킵니다. 즉, 외래 키의 열 이름
  • referencedColumnName 속성은 연관 / 참조 된 엔티티의 관련 열, 즉 기본 키의 열 이름을 가리 킵니다.

referencedColumnName참조 된 엔터티에 PK로 단일 열이 있는 경우에는 해당 항목이 참조하는 열 (즉, Address단일 열 ID) 이 확실하기 때문에 채울 필요 가 없습니다 .

@ManyToOne
@JoinColumn(name="ADDR_ID")
public Address getAddress() { return address; }

그러나 참조 된 엔터티에 여러 열에 걸쳐있는 PK가있는 경우 @JoinColumn주석 을 지정하는 순서 가 중요합니다. referencedColumnName지정 하지 않아도 작동 할 수 있지만 운 이 좋을 뿐입니다. 따라서 다음과 같이 매핑해야합니다.

@ManyToOne
@JoinColumns({
    @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
    @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
public Address getAddress() { return address; }

또는 다음의 경우 ManyToMany:

@ManyToMany
@JoinTable(
    name="CUST_ADDR",
    joinColumns=
        @JoinColumn(name="CUST_ID"),
    inverseJoinColumns={
        @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
        @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
    }
)

실제 사례

참조 된 열이 지정되지 않은 동일한 조인 테이블 매핑의 Hibernate에 의해 생성 된 두 개의 쿼리. 주석 의 순서 만 @JoinColumn변경되었습니다.

/* load collection Client.emails */ 
select 
emails0_.id_client as id1_18_1_,
emails0_.rev as rev18_1_,
emails0_.id_email as id3_1_,
email1_.id_email as id1_6_0_

from client_email emails0_ 
inner join email email1_ on emails0_.id_email=email1_.id_email 

where emails0_.id_client='2' and 
emails0_.rev='18'
/* load collection Client.emails */ 
select
emails0_.rev as rev18_1_,
emails0_.id_client as id2_18_1_,
emails0_.id_email as id3_1_, 
email1_.id_email as id1_6_0_

from client_email emails0_ 
inner join email email1_ on emails0_.id_email=email1_.id_email 

where emails0_.rev='2' and 
emails0_.id_client='18'

We are querying a join table to get client's emails. The {2, 18} is composite ID of Client. The order of column names is determined by your order of @JoinColumn annotations. The order of both integers is always the same, probably sorted by hibernate and that's why proper alignment with join table columns is required and we can't or should rely on mapping order.

The interesting thing is the order of the integers does not match the order in which they are mapped in the entity - in that case I would expect {18, 2}. So it seems the Hibernate is sorting the column names before it use them in query. If this is true and you would order your @JoinColumn in the same way you would not need referencedColumnName, but I say this only for illustration.

Properly filled referencedColumnName attributes result in exactly same query without the ambiguity, in my case the second query (rev = 2, id_client = 18).


For a JPA 2.x example usage for the general case of two tables, with a @OneToMany unidirectional join see https://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Example_of_a_JPA_2.x_unidirectional_OneToMany_relationship_annotations

Screenshot from this WikiBooks JPA article: Example of a JPA 2.x unidirectional OneToMany relationship database

참고URL : https://stackoverflow.com/questions/11244569/what-is-referencedcolumnname-used-for-in-jpa

반응형