name vs referencedColumnName

엔티티 필드에 연관관계를 설정할 때 @JoinColumn 어노테이션을 사용할 수 있다.

@JoinColumn 의 속성 중 name 과 referencedColumnName 가 혼동돼서 정리해두려고 한다.

두 속성은 외래키와 연관이 있다. 외래키는 한 테이블에서 다른 테이블의 행을 식별하기 위해 사용한다.


name

The name of the foreign key column.


자신의 테이블에 선언한 외래키 컬럼명이다.

다른 테이블의 행을 식별하기 위해 해당 테이블에 선언한 외래키의 컬럼명을 뜻한다.


referencedColumnName

The name of the column referenced by this foreign key column.


참조하는 테이블에 선언된 컬럼명이다.

자신의 테이블에 선언한 외래키로 조회하는 참조 테이블의 컬럼명을 나타낸다.

별도로 선언하지 않으면 디폴트로 참조 테이블의 PK(Primary Key) 컬럼명이 설정된다.


예시

create table post 
(
    id int primary key auto_increment,
    title varchar(50) not null,
    content varchar(200) not null
);
create table comment 
(
    id int primary key auto_increment,
    post_id int not null,
    content varchar(200) not null,
    foreign key (post_id) references post(id)
);

post, comment 테이블의 구조는 위와 같다.



@Entity
@Table(name = "post")
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(length = 50, nullable = false)
    private String title;

    @Column(length = 200, nullable = false)
    private String content;

    @OneToMany(mappedBy = "post")
    private List<Comment> comments;
}
@Entity
@Table(name = "comment")
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "post_id", nullable = false)
    private Post post;

    @Column(length = 200, nullable = false)
    private String content;
}

post, comment 테이블을 엔티티로 각각 Post, Comment 로 표현했다.

두 엔티티는 1:N 양방향 연관관계를 맺는다.


Comment 엔티티의 @JoinColumn 어노테이션의 name 속성 값으로 post_id 를 설정했다. comment 테이블에서 post 테이블의 id 컬럼을 조회할 외래키를 post_id 로 설정했다. name 속성 값은 이 post_id 를 가리킨다.


위 예시에서 Comment 엔티티의 @JoinColumn 어노테이션에 referencedColumnName 을 작성하지 않았지만 만약에 작성한다면 id 로 작성하면 된다. post 테이블의 pk 컬럼명이 id 다.



<참고>

https://ko.wikipedia.org/wiki/%EC%99%B8%EB%9E%98_%ED%82%A4

https://jakarta.ee/specifications/persistence/3.1/apidocs/jakarta.persistence/jakarta/persistence/joincolumn

https://velog.io/@beomdrive/JPA-%EB%A7%A4%ED%95%91-%EA%B8%B0%EC%B4%88-JoinColumn

'Dev > Database' 카테고리의 다른 글

트랜잭션 격리 수준  (0) 2023.08.25
Clustered Index & Non Clustered Index  (0) 2023.05.10
TypeORM - getMany vs getRawMany  (0) 2023.02.21

+ Recent posts