JPA에서 상속 관계 매핑은 객체 지향의 상속 개념을 관계형 데이터베이스에 효과적으로 매핑하는 방법을 제공합니다. @Inheritance 어노테이션을 사용하여 구현할 수 있으며, 크게 세 가지 전략이 있습니다.
부모 클래스와 자식 클래스를 각각의 테이블로 매핑하고, 조인을 통해 함께 조회하는 방식입니다.
구현 방식:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "DTYPE") // 구분 컬럼
public abstract class Item {
@Id @GeneratedValue
private Long id;
private String name;
private int price;
}
@Entity
@DiscriminatorValue("A") // 구분 값
public class Album extends Item {
private String artist;
}
@Entity
@DiscriminatorValue("M")
public class Movie extends Item {
private String director;
private String actor;
}
장점:
단점:
모든 자식 클래스를 하나의 테이블에 통합하여 매핑하는 방식입니다. 구분 컬럼(DTYPE)으로 어떤 자식 엔티티인지 구분합니다.
구현 방식:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "DTYPE")
public abstract class Item {
@Id @GeneratedValue
private Long id;
private String name;
private int price;
}
@Entity
@DiscriminatorValue("A")
public class Album extends Item {
private String artist;
}
@Entity
@DiscriminatorValue("M")
public class Movie extends Item {
private String director;
private String actor;
}
장점:
단점:
자식 클래스마다 별도의 테이블을 만들고, 각 테이블에 필요한 컬럼을 모두 포함하는 방식입니다.
구현 방식:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Item {
@Id @GeneratedValue
private Long id;
private String name;
private int price;
}
@Entity
public class Album extends Item {
private String artist;
}
@Entity
public class Movie extends Item {
private String director;
private String actor;
}
장점:
단점: