[JPA] 상속 관계 매핑

HAEN·2023년 1월 9일
0

JPA

목록 보기
4/5

1. 상속관계 매핑이란?

  • 객체에는 상속이 존재하지만, 관계형 데이터베이스에는 상속 관계가 존재하지 않음
  • 데이터베이스 설계에서 슈퍼타입-서브타입 관계라는 논리적 모델링 기법이 객체 상속과 유사

    상속관계 매핑: 객체의 상속 구조와 DB의 슈퍼타입 서브타입 관계를 매핑하는 것


2. 매핑 구현 기법

(1) 조인 @Inheritance(strategy = InheritanceType.JOINED)

부모 엔티티 테이블의 기본키를 외래키로 가져와 자식 엔티티 테이블의 기본키로 사용

@Entity
@Inheritance(strategy = IngeritanceType.JOINED)
class abstract Item { // abstract를 통해 추상 클래스로 사용
	@Id @GeneratedValue
    private Long id;
    private String name;
    private int price;
    ...
}

@Entity
class Album extends Item { // Item 클래스를 상속
	private String artist;
    ...
}

@Entity
class Movie extends Item { // Item 클래스를 상속
	private String director;
    private String actor;
    ...
}

@Entity
class Book extends Item { // Item 클래스를 상속
	private String author;
    private String isbn;
    ...
}

(2) 단일 테이블 @Inheritance(strategy = InheritanceType.SINGLE_TABLE)

상속관계 매핑 기본값
자식 엔티티들의 속성을 부모 엔티티에 집합
-> DTYPE 표시 필수(@DiscriminatorColumn)

@Entity
@Inheritance(strategy = IngeritanceType.SINGLE_TABLE) // strategy 생략 가능
class Item { 
	@Id @GeneratedValue
    private Long id;
    private String name;
    private int price;
    ...
}

// 자식 엔티티들은 위와 동일

(3) 구현 클래스마다 각각의 테이블 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

부모 엔티티의 테이블이 만들어지지 않고 자식 엔티티의 테이블들만 만들어짐

@Entity
@Inheritance(strategy = IngeritanceType.TABLE_PER_CLASS)
class abstract Item { // abstract를 통해 추상 클래스로 사용
	@Id @GeneratedValue
    private Long id;
    private String name;
    private int price;
    ...
}

// 자식 엔티티들은 위와 동일

3. 정리

객체 지향의 방향성과 부합한 조인 전략을 기본적으로 사용하되, 변경 가능성이 낮다면 단일 테이블 전략으로 사용하는 것을 고민
구현 클래스마다 각각의 테이블을 만드는 것은 성능이 느리고 복잡하기 때문에 권장 X




참고: 인프런 자바 ORM 표준 JPA 프로그래밍 기본편 - 김영한
profile
핸수

0개의 댓글