문제 상황
토이 프로젝트 진행 중 상속 관계 매핑을 싱글 테이블 전략으로 진행했다.
아래는 상속 관계에 있는 클래스의 다이어그램이다.

공통 사항은 Study 필드에 있고 자식 클래스들의 세부사항은 각각의 필드에 있다. 이 때 StudyRepository 하나로 기본적인 CRUD작업을 할 경우 해당 행의 타입이 어떤 타입인지 구분하기가 어려웠다. 예를 들어, id값으로 데이터를 조회할 때 해당 row의 타입이 무엇인지 알 수 없기 때문에 데이터를 매핑할 Entity의 타입을 지정할 수 없었다. 물론 요청이 들어올 때 타입을 구분하는 변수를 하나 추가하고 자식 클래스별로 repository를 만들면 해결 할 수도 있다. 하지만 상속 관계 매핑 시 @DiscriminatorColumn을 통해 DB에 생성되는 필드가 있기 때문에 이를 활용하고 싶었다.
해결 방안
최초엔 Study 엔티티에 discriminator column을 매핑할 수 있는 필드를 생성했다. 하지만 중복이라며 오류가 발생했고 구글링을 통해 읽기전용으로 생성해야 함을 알게 됐다.
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@DiscriminatorColumn(name = "study_type")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Entity
public abstract class Study extends BaseInfoEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="study_type", insertable = false, updatable = false)
private String studyType;
.
.
.
.
}
참고 :
https://stackoverflow.com/questions/43570875/how-to-access-discriminator-column-in-jpa
How to access discriminator column in JPA
I have DisseminationArea as subcalss for Feature with the following code: @Entity @Table(name = "features") @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name = "subtype_id",
stackoverflow.com
'JPA' 카테고리의 다른 글
[JPA] GenerationTarget encountered exception accepting command : Error executing DDL - Oracle (0) | 2023.06.14 |
---|