슈퍼-서브 타입을 사용하려면 슈퍼 테이블과 여러개의 서브 테이블이 생긴다
Super
슈퍼 클래에는
@Inheritance 와 @DiscriminatorColumn이 있다.
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "DType")
@Inheritance
@Inheritance에는 상속 전략을 정할 수 있다.
strategy = InheritanceType.SINGLE_TABLE
싱글 테이블 전략으로 서브 테이블들을 클래스로 나누어 구현하지만 실제 DB에서는 서브 클래스 들의 컬럼들이 모두 null이 입력 가능한 형태로 합쳐저 하나의 테이블로 만들어 진다.
이 경우에는 서브 테이블 들이 모두 합쳐지므로, 서브 클래스에 @Table 로 테이블 이름을 지정해 줄 수 없고 슈퍼 클래스의 테이블 이름을 가져간다.
아래는 위의 그림이 SINGLE_TABLE 전략으로 실핸된 hibernate의 DDL이다.
Hibernate:
create table script (
created_at date not null,
total_expect_time time(6),
total_real_time time(6),
script_id bigint not null,
dtype varchar(31) not null,
script_content varchar(255) not null,
version_fk varbinary(255),
primary key (script_id)
) engine=InnoDB
strategy = InheritanceType.JOINED
만드는 서브 클래스 마다 테이블이 하나씩 생기게 된다.
아래는 위의 그림을 JOINED로 설정했을때의 hibernate의 DDL 이다.
Hibernate:
create table script (
created_at date not null,
script_id bigint not null,
dtype varchar(31) not null,
script_content varchar(255) not null,
version_fk varbinary(255),
primary key (script_id)
) engine=InnoDB
Hibernate:
create table script_sub_entity (
total_expect_time time(6),
script_id bigint not null,
primary key (script_id)
) engine=InnoDB
Hibernate:
create table sttscript_sub_entity (
total_real_time time(6),
script_id bigint not null,
primary key (script_id)
) engine=InnoDB
strategy = InheritanceType.TABLE_PER_CLASS
슈퍼 클래스와 서브 클래스가 모두 테이블로 만들어지고 서브 테이블이 슈퍼 테이블의 컬럼을 모두 가지고 있는 형태로 만들어 진다.
아래는 TABLE_PER_CLASS 전략으로 실행된 hibernate의 DDL 이다.
Hibernate:
create table script (
created_at date not null,
script_id bigint not null,
script_content varchar(255) not null,
version_fk varbinary(255),
primary key (script_id)
) engine=InnoDB
Hibernate:
create table script_sub_entity (
created_at date not null,
total_expect_time time(6),
script_id bigint not null,
script_content varchar(255) not null,
version_fk varbinary(255),
primary key (script_id)
) engine=InnoDB
Hibernate:
create table sttscript_sub_entity (
created_at date not null,
total_real_time time(6),
script_id bigint not null,
script_content varchar(255) not null,
version_fk varbinary(255),
primary key (script_id)
) engine=InnoDB
@DiscriminatorColumn(name = "")
이 어노테이션은 슈퍼 테이블에 서브 테이블의 종류를 구별하는 column을 하나 만들어 준다.
Default 값은 "DType"이다.
Sub
서브 클래스에는 @DiscriminatorValue 가 있다.
@DiscriminatorValue("input")
@DiscriminatorValue
슈퍼 클래스에 있는 @DiscrimnatorColumn과 관계가 있는데
@DiscrimnatorColumn은 서브 클래스의 종류를 구별해 주는 column이름이 들어가고 @DiscrimnatorValue는 그 칼럼이 가질 수 있는 값들이 들어간다.
@DiscriminatorValue("input")
@Entity
public class ScriptSubEntity extends ScriptSuperEntity {
private LocalTime total_expect_time;
}
서브 클래스는 슈퍼 클래스를 상속하고, 서브 클래스 만의 컬럼만 적어주면 된다.
https://ict-nroo.tistory.com/128
https://velog.io/@cham/JPA-%EC%83%81%EC%86%8D-%EA%B4%80%EA%B3%84-Mapping-%EC%A0%95%EB%A6%AC